Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need an explanation on this code - c#

I am getting familiar with C# day by day and I came across this piece of 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 fail to follow is that how does the delegate get notified that the copy is done? Say after the copy is done I want to perform an operation on the copied file.

And yes I do know that this may beyond me given my few years in C#.

like image 452
ltech Avatar asked Apr 19 '26 10:04

ltech


1 Answers

The

done(exc);

and

else done(null);

bits execute the Action<Exception> which in turn will call the Action<Stream, Stream, Exception> passed into it using the completed parameter.

This is done using AsyncOperation.Post so that the completed delegate is executed on an appropriate thread.

EDIT: You'd use it something like this:

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
    }
}

Or you could use a lambda expression or anonymous method - it depends on how much logic you need.

like image 59
Jon Skeet Avatar answered Apr 23 '26 16:04

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!