c#-3.0 – 需要对此代码进行说明 – c#

我日复一日地熟悉C#,我遇到了这段代码

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);

}

从这篇文章
Article

我没有遵循的是,如何通知代表副本已完成?复制完成后说我想对复制的文件执行操作.

是的,我确实知道这可能超出了我在C#中的几年.

最佳答案

done(exc);

else done(null);

位执行Action< Exception>反过来,它将调用Action< Stream,Stream,Exception>使用完成的参数传递给它.

这是使用AsyncOperation.Post完成的,以便在适当的线程上执行完成的委托.

编辑:你会使用这样的东西:

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

或者你可以使用lambda表达式或匿名方法 – 它取决于你需要多少逻辑.

转载注明原文:c#-3.0 – 需要对此代码进行说明 – c# - 代码日志