C# 什么是异步回调?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1047662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 06:56:55  来源:igfitidea点击:

What is AsyncCallback?

c#asynchronous

提问by RV.

What is the use of AsyncCallback and why should we use it?

AsyncCallback 有什么用,为什么要使用它?

采纳答案by SO User

When the asyncmethod finish the processing, AsyncCallbackmethod is automatically called, where post processing statements can be executed. With this technique there is no need to poll or wait for the asyncthread to complete.

当该async方法完成处理时,AsyncCallback会自动调用方法,在那里可以执行后处理语句。使用此技术,无需轮询或等待async线程完成。

Here's some more explanation on AsyncCallback usage:

这里有一些关于Async回调用法的更多解释:

Callback Model:The callback model requires that we specify a method to callback on and include any state that we need in the callback method to complete the call. The callback model can be seen in the following example:

回调模型:回调模型要求我们指定一个回调方法,并在回调方法中包含完成调用所需的任何状态。回调模型可以在以下示例中看到:

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

In this model, we are creating a new AsyncCallbackdelegate, specifying a method to call (on another thread) when the operation is complete. Additionally, we are specifying some object that we might need as the state of the call. For this example, we are sending the stream object in because we will need to call EndReadand close the stream.

在这个模型中,我们正在创建一个新的AsyncCallback委托,指定一个在操作完成时(在另一个线程上)调用的方法。此外,我们指定了一些我们可能需要作为调用状态的对象。对于这个例子,我们发送流对象是因为我们需要调用EndRead和关闭流。

The method that we create to be called at the end of the call would look something like this:

我们创建的在调用结束时调用的方法看起来像这样:

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

Other techniques are Wait-until-doneand Polling.

其他技术是Wait-until-donePolling

Wait-Until-Done ModelThe wait-until-done model allows you to start the asynchronous call and perform other work. Once the other work is done, you can attempt to end the call and it will block until the asynchronous call is complete.

等待完成模型等待完成模型允许您启动异步调用并执行其他工作。其他工作完成后,您可以尝试结束调用,它会阻塞,直到异步调用完成。

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

Or you can use wait handles.

或者您可以使用等待句柄。

result.AsyncWaitHandle.WaitOne();

Polling ModelThe polling method is similar, with the exception that the code will poll the IAsyncResultto see whether it has completed.

轮询模型轮询方法类似,只是代码会轮询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);
}

回答by heavyd

AsyncCallbacks are used to specify a function to call when an asynchronous operation is completed. For example, if you were doing an IO operation you would call BeginRead on a stream and pass in an AsyncCAllback delegate. The function would be called when the read operation completed.

AsyncCallbacks 用于指定在异步操作完成时要调用的函数。例如,如果您正在执行 IO 操作,您将在流上调用 BeginRead 并传入 AsyncCAllback 委托。当读取操作完成时将调用该函数。

For more information see:

有关更多信息,请参阅:

回答by bobbyalex

Think of it this way. You have some operations that you would like to execute in parallel. You would enable this by using threads which executes asynchronously. This is a fire and forget mechanism.

这么想吧。您有一些想要并行执行的操作。您可以通过使用异步执行的线程来启用此功能。这是一个即发即忘的机制。

But some situations call for a mechanism where you can fire and forget but need notification when the operation completes. For this you would use an async call back.

但是有些情况需要一种机制,您可以在其中触发并忘记,但在操作完成时需要通知。为此,您将使用异步回调。

The operation is async but calls you back when the operation completes. The advantage of this is that you dont have to wait on the operation till it completes. You are free to execute other operations and hence your thread is not blocked.

该操作是异步的,但在操作完成时给您回电。这样做的好处是您不必等待操作完成。您可以自由执行其他操作,因此您的线程不会被阻塞。

An example of this would be a background transfer of a large file. While the transfer is in progress you dont really want to block the user from doing other operations. Once the transfer is complete the process will call you back on an async method, where you can probably pop up a message box which says 'Transfer complete'

这方面的一个例子是大文件的后台传输。在传输过程中,您真的不想阻止用户进行其他操作。传输完成后,该过程将通过异步方法回叫您,您可能会在其中弹出一个消息框,上面写着“传输完成”