异步回调
回调在异步情况下最有用。前面实例中说明的回调是同步回调,也就是按顺序调用函数。如
果
AddTwoNumbers 方法花费较长时间来执行,则该函数之后的所有的语句将被阻塞。
组织较好的方式是异步调用
AddTwoNumbers 方法。异步调用函数允许主程序继续执行,而
不需要等待该函数返回。
在这种异步模型中,当调用
AddTwoNumbers 函数时,在其后的语句继续执行。当函数结束
时,他调用
ResultCallback 函数。
下面使用异步回调重写前面的程序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;
namespace DelegateCallBack
{
class Program
{
delegate int MethodDelegate(int num1, int num2);
static void Main(string[] args)
{
MethodDelegate result = AddTwoNumbers;
//引用异步操作完成时调用的方法
AsyncCallback callback = new AsyncCallback(ResultCallback);
Console.WriteLine("开始异步调用");
IAsyncResult iresult = result.BeginInvoke(5, 3, callback, null);
Console.WriteLine("主程序继续执行");
Console.Read();
}