using System; using System.Collections.Generic; using System.Runtime.Remoting.Messaging; using System.Threading; namespace asyncResult { delegate long myDel(int first,int second); class Program { static void Main(string[] args) { Console.WriteLine("Main begin"); IAsyncResult iar = new myDel(Sum).BeginInvoke(3, 5, CallBackAsyn, null); Console.WriteLine("Doing more work in Main"); Thread.Sleep(500); Console.WriteLine("Done with Main Exiting"); } static long Sum(int first, int second) { Console.WriteLine("delete method Begin"); Thread.Sleep(100); return first + second; } //怎么确保回调函数是由哪个异步线程发起的? //这就是为什么需要用IAsyncResult接口的原因,IAsyncResult接口对象在AsyncResult 类对象内部,AsyncResult包含委托对象引用 static void CallBackAsyn(IAsyncResult iar) { Console.WriteLine("CallBackFn asyncResult Begin"); AsyncResult ar = (AsyncResult)iar; myDel del = (myDel)ar.AsyncDelegate; Console.WriteLine("CallBackFn asyncResult result is:{0}",del.EndInvoke(iar)); } } }