C# -- 等待异步操作执行完成的方式
等待异步操作的完成,代码实现
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 Func<int, int> mySum1 = SumNumbers; 6 Func<int, int> mySum2 = SumNumbers; 7 Func<int, int> mySum3 = SumNumbers; 8 9 AsyncCallback callback = c => Console.WriteLine("线程ID:{0},回调函数执行:{1}",Thread.CurrentThread.ManagedThreadId,c.AsyncState); 10 11 12 IAsyncResult result1= mySum1.BeginInvoke(10000, callback, "第一个异步"); 13 IAsyncResult result2= mySum2.BeginInvoke(10000, callback, "第二个异步"); 14 IAsyncResult result3= mySum3.BeginInvoke(10000, callback, "第三个异步"); 15 16 17 //异步等待方式1:使用EndInvoke 18 int asyc1 = mySum1.EndInvoke(result1); 19 Console.WriteLine("第一个异步已经执行完成,结果:{0}",asyc1); 20 21 //异步等待方式2:使用AsyncWaitHandle.WaitOne,参数-1表示一直等待到执行完成 22 if (result2.AsyncWaitHandle.WaitOne(-1)) 23 { 24 Console.WriteLine("第二个异步执行完成"); 25 } 26 27 //异步等待方式3:使用IsCompleted判断 28 while (!result3.IsCompleted) 29 { 30 Console.WriteLine("第三个异步还在执行中...."); 31 Thread.Sleep(300); 32 } 33 Console.WriteLine("第三个异步执行完成"); 34 35 Console.ReadKey(); 36 } 37 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 } 45 46 Thread.Sleep(3000); 47 return sum; 48 } 49 }
代码执行结果: