3 static void Main(string[] args) 4 { 5 Func mySum1 = SumNumbers; 6 Func mySum2 = SumNumbers; 7 Func mySum3 = SumNumbers; 9 AsyncCallback callback = c => Console.WriteLine("线程ID:{0},回调函数执行:{1}",Thread.CurrentThread.ManagedThreadId,c.AsyncState); 12 IAsyncResult result1= mySum1.BeginInvoke(10000, callback, "第一个异步"); 13 IAsyncResult result2= mySum2.BeginInvoke(10000, callback, "第二个异步"); 14 IAsyncResult result3= mySum3.BeginInvoke(10000, callback, "第三个异步"); 17 //异步等待方式1:使用EndInvoke 18 int asyc1 = mySum1.EndInvoke(result1); 19 Console.WriteLine("第一个异步已经执行完成,结果:{0}",asyc1); 21 //异步等待方式2:使用AsyncWaitHandle.WaitOne,参数-1表示一直等待到执行完成 22 if (result2.AsyncWaitHandle.WaitOne(-1)) 23 { 24 Console.WriteLine("第二个异步执行完成"); 25 } 27 //异步等待方式3:使用IsCompleted判断 28 while (!result3.IsCompleted) 29 { 30 Console.WriteLine("第三个异步还在执行中...."); 31 Thread.Sleep(300); 32 } 33 Console.WriteLine("第三个异步执行完成"); 35 Console.ReadKey(); 36 } 38 public static int SumNumbers(int count) 39 { 40 int sum = 0; 41 for (int i = 0; i < count; i++) 42 { 43 sum += i; 44 } 46 Thread.Sleep(3000); 47 return sum; 48 } 49 }

代码执行结果: