1 //定义一个委托 2 static Func<int, int, string> delFunc = (a, b) => 3 { 4 Console.WriteLine("委托线程:" + Thread.CurrentThread.ManagedThreadId); 5 return (a + b).ToString(); 6 }; 7 8 static void Main(string[] args) 9 { 10 Console.WriteLine("主线程:" + Thread.CurrentThread.ManagedThreadId); 11 12 //同步调用委托 13 //string str = delFunc(3,4);//str = delFunc.Invoke(3, 4); 14 15 //异步调用委托(原理:用线程池中线程,执行委托指向的方法) 16 IAsyncResult ar = delFunc.BeginInvoke(3, 4, CallBackFn, "我是回调函数参数");//回调函数和回调函数参数 17 //string result = delFunc.EndInvoke(ar);//EndInvoke方法会阻塞,等待异步委托的结束 18 19 Console.ReadLine(); 20 } 21 22 //异步委托执行完成后,回调的函数 23 static void CallBackFn(IAsyncResult iar) 24 { 25 object obj = iar.AsyncState;//我是回调函数参数 26 27 AsyncResult ar = iar as AsyncResult; 28 Func<int, int, string> del = ar.AsyncDelegate as Func<int, int, string>; 29 string result = del.EndInvoke(ar);//异步委托的结果,在这里委托已经执行完毕,不会再阻塞。 30 31 Console.WriteLine("回调线程:" + Thread.CurrentThread.ManagedThreadId); 32 }