每个委托都有3个方法 : Invoke : 是委托指定函数的同步调用; BeginInvoke : 是异步调用, 调用后立即返回,不等待调用结果 EndInvoke : 是异步调用, 用于检索调用结果。调用BeginInvoke后可随时调用, 它将一直阻塞到异步调用完成。 AsyncCallback 委托 : 用于指定在开始操作完成后应被调用的方法。 IAsyncResult 接口 : 用于监视和管理异步操作。 public interface IAsyncResult { Object AsyncState { get; } // 该属性为BeginInvoke参数中的最后一个参数对象 WaitHandle AsyncWaitHandle { get; } // bool CompletedSynchronously { get; } // 如果开始操作调用已同步完成,则其属性将被设置为 true。 bool IsCompleted { get; } // 该属性判断异步调用是否结束 }
例子 : 1) 定义一个委托 :
public delegate int AddHandler(int a, int b);
2)加法类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace BeginInvokeDemo
{
public class AddOperation
{
public static int Add(int a, int b)
{
Console.WriteLine("开始计算:" + a + "+" + b);
Thread.Sleep(3000); //模拟该方法运行三秒
Console.WriteLine("计算完成!");
return a + b;
}
}
}
3) 同步调用,异步调用,异步回调
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Remoting.Messaging;
namespace BeginInvokeDemo
{
public delegate int AddHandler(int a, int b);
class Program
{
static void Main(string[] args)
{
//Console.WriteLine("===== 同步调用 SyncInvokeTest =====");
//AddHandler handler = new AddHandler(AddOperation.Add);
//int result = handler.Invoke(1, 2);
//Console.WriteLine("继续做别的事情。。。");
//Console.WriteLine(result);
//Console.ReadKey();
//Console.WriteLine("===== 异步调用 AsyncInvokeTest =====");
//AddHandler handler = new AddHandler(AddOperation.Add);
IAsyncResult: 异步操作接口(interface)
BeginInvoke: 委托(delegate)的一个异步方法的开始
//IAsyncResult result = handler.BeginInvoke(1, 2, null, null);
//Console.WriteLine("继续做别的事情。。。");
异步操作返回
//Console.WriteLine(handler.EndInvoke(result));
//Console.ReadKey();
Console.WriteLine("===== 异步回调 AsyncInvokeTest =====");
AddHandler handler = new AddHandler(AddOperation.Add);
//异步操作接口(注意BeginInvoke方法的不同!)
IAsyncResult result = handler.BeginInvoke(1, 2, new AsyncCallback(CallBack), "AsycState:OK");
Console.WriteLine("继续做别的事情。。。");
Console.ReadKey();
}
static void CallBack(IAsyncResult result)
{ //result 是“加法类.Add()方法”的返回值
//AsyncResult 是IAsyncResult接口的一个实现类,空间:System.Runtime.Remoting.Messaging
//AsyncDelegate 属性可以强制转换为用户定义的委托的实际类。
AddHandler handler = (AddHandler)((AsyncResult)result).AsyncDelegate;
Console.WriteLine(handler.EndInvoke(result));
Console.WriteLine(result.AsyncState);
}
}
}