AsyncCallback的用途是什么?我们为什么要使用它?
发布于 2009-06-26 06:44:23
当async方法完成处理时,将自动调用AsyncCallback方法,可以在该方法中执行后期处理语句。使用这种技术,不需要轮询或等待async线程完成。
下面是关于Async回调用法的更多解释:
回调模型:回调模型要求我们指定一个回调方法,并在回调方法中包含完成调用所需的任何状态。回调模型如下例所示:
static byte[] buffer = new byte[100];
static void TestCallbackAPM()
{
string filename = System.IO.Path.Combine (System.Environment.CurrentDirectory, "mfc71.pdb");
FileStream strm = new FileStream(filename,
FileMode.Open, FileAccess.Read, FileShare.Read, 1024,
FileOptions.Asynchronous);
// Make the asynchronous call
IAsyncResult result = strm.BeginRead(buffer, 0, buffer.Length,
new AsyncCallback(CompleteRead), strm);
}在这个模型中,我们创建了一个新的AsyncCallback委托,指定一个在操作完成时(在另一个线程上)调用的方法。此外,我们还指定了一些可能需要的对象作为调用的状态。对于本例,我们将发送流对象,因为我们将需要调用EndRead并关闭流。
我们创建的方法将在调用结束时被调用,如下所示:
static void CompleteRead(IAsyncResult result)
{
Console.WriteLine("Read Completed");
FileStream strm = (FileStream) result.AsyncState;
// Finished, so we can call EndRead and it will return without blocking
int numBytes = strm.EndRead(result);
// Don't forget to close the stream
strm.Close();
Console.WriteLine("Read {0} Bytes", numBytes);
Console.WriteLine(BitConverter.ToString(buffer));
}其他技术有Wait-until-done和Polling。
等待完成模型等待完成模型允许您启动异步调用并执行其他工作。一旦其他工作完成,您可以尝试结束调用,它将阻塞,直到异步调用完成。
// Make the asynchronous call
strm.Read(buffer, 0, buffer.Length);
IAsyncResult result = strm.BeginRead(buffer, 0, buffer.Length, null, null);
// Do some work here while you wait
// Calling EndRead will block until the Async work is complete
int numBytes = strm.EndRead(result);或者,您可以使用等待句柄。
result.AsyncWaitHandle.WaitOne();轮询模型轮询方法类似,不同之处在于代码将轮询IAsyncResult以查看它是否已完成。
// Make the asynchronous call
IAsyncResult result = strm.BeginRead(buffer, 0, buffer.Length, null, null);
// Poll testing to see if complete
while (!result.IsCompleted)
{
// Do more work here if the call isn't complete
Thread.Sleep(100);
}发布于 2009-06-26 07:01:57
这样想吧。您有一些想要并行执行的操作。您可以通过使用异步执行的线程来启用此功能。这是一种即发即忘的机制。
但有些情况需要一种机制,在这种机制下,您可以触发并忘记,但在操作完成时需要通知。为此,您将使用异步回调。
该操作是异步的,但会在操作完成时回调您。这样做的好处是,您不必等待操作完成。您可以自由执行其他操作,因此您的线程不会被阻塞。
这方面的一个例子是大文件的后台传输。在传输过程中,您不会真的想阻止用户执行其他操作。一旦传输完成,该过程将在异步方法上回调您,在该方法中,您可能会弹出一个消息框,上面显示“传输完成”。
发布于 2009-06-26 06:48:13
AsyncCallbacks用于指定异步操作完成时要调用的函数。例如,如果您正在进行IO操作,您将在一个流上调用BeginRead并传入一个AsyncCAllback委托。该函数将在读取操作完成时调用。
有关详细信息,请参阅:
https://stackoverflow.com/questions/1047662
复制相似问题