我日复一日地熟悉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);
Run Code Online (Sandbox Code Playgroud)
}
来自本文的 文章
我没有遵循的是,如何通知代表副本已完成?复制完成后说我想对复制的文件执行操作.
是的,我确实知道这可能超出了我在C#中的几年.
该
done(exc);
Run Code Online (Sandbox Code Playgroud)
和
else done(null);
Run Code Online (Sandbox Code Playgroud)
位执行Action<Exception>,然后Action<Stream, Stream, Exception>使用completed参数调用传递给它的位.
这是使用,AsyncOperation.Post以便completed委托在适当的线程上执行.
编辑:你会使用这样的东西:
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
}
}
Run Code Online (Sandbox Code Playgroud)
或者你可以使用lambda表达式或匿名方法 - 它取决于你需要多少逻辑.