Need to clarify this code - C #

I am familiar with C # day after day and I came across this part of the code

public static void CopyStreamToStream(
Stream source, Stream destination, 
Action<Stream,Stream,Exception> completed) {
byte[] buffer = new byte[0x1000];
AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(null);

Action<Exception> done = e => {
    if (completed != null) asyncOp.Post(delegate { 
        completed(source, destination, e); }, null);
};

AsyncCallback rc = null;
rc = readResult => {
    try {
        int read = source.EndRead(readResult);
        if (read > 0) {
            destination.BeginWrite(buffer, 0, read, writeResult => {
                try {
                    destination.EndWrite(writeResult);
                    source.BeginRead(
                        buffer, 0, buffer.Length, rc, null);
                }
                catch (Exception exc) { done(exc); }
            }, null);
        }
        else done(null);
    }
    catch (Exception exc) { done(exc); }
};

source.BeginRead(buffer, 0, buffer.Length, rc, null);

}

From this article. Article

What I don’t understand is how does the delegate get a notification that the copy is complete? Say, after copying is complete, I want to perform an operation on the copied file.

And yes, I know that this can exceed me, given my several years in C #.

+3
source share
4 answers

done(exc);

and

else done(null);

a bit executes Action<Exception>, which, in turn, calls Action<Stream, Stream, Exception>passed to it using a parameter completed.

This is done with help AsyncOperation.Post, so that the delegate completedis executed in the appropriate thread.

EDIT: :

CopyStreamToStream(input, output, CopyCompleted);
...

private void CopyCompleted(Stream input, Stream output, Exception ex)
{
    if (ex != null)
    {
        LogError(ex);
    }
    else
    {
        // Put code to notify the database that the copy has completed here
    }
}

- - , .

+5

, done. catch, else AsyncCallback, , , BeginRead:

AsyncCallback rc = null;
rc = readResult => {
    try {
        int read = source.EndRead(readResult);
        if (read > 0) {
            destination.BeginWrite(buffer, 0, read, writeResult => {
                try {
                    destination.EndWrite(writeResult);
                    source.BeginRead(
                        buffer, 0, buffer.Length, rc, null);
                }
                catch (Exception exc) { done(exc); }  // <-- here
            }, null);
        }
        else done(null);   // <-- here
    }
    catch (Exception exc) { done(exc); }   // <-- and here
};
+2

done(...) - , . i.e.

Action<Exception> done = e => {  
    if (completed != null) asyncOp.Post(delegate {   
        completed(source, destination, e); }, null);  
};  
+1

@ltech - ? : for , ?

0

Source: https://habr.com/ru/post/1741104/


All Articles