一、异步委托第一种使用方式
异步调用委托,其实就是使用了一个线程池去执行了委托执行的方法。
1 static void Main(string[] args) 2 { 3 Console.WriteLine("当前主线程:" + Thread.CurrentThread.ManagedThreadId); 4 5 Func<int, int, string> delFunc = new Func<int, int, string>((a, b) => { 6 Console.WriteLine("Asynchronous Delegate:"+Thread.CurrentThread.ManagedThreadId); 7 return ((a + b).ToString()); 8 9 }); 10 11 12 13 IAsyncResult asyncRes= delFunc.BeginInvoke(2,3,null,null); 14 15 16 //string str = delFunc(1, 2); 17 //Console.WriteLine(str); 18 19 Console.ReadKey(); 20 }
二、异步委托第二种使用方式
1 static void Main(string[] args) 2 { 3 Console.WriteLine("当前主线程:" + Thread.CurrentThread.ManagedThreadId); 4 5 Func<int, int, string> delFunc = new Func<int, int, string>((a, b) => { 6 Console.WriteLine("Asynchronous Delegate:"+Thread.CurrentThread.ManagedThreadId); 7 Thread.Sleep(3000); 8 return ((a + b).ToString()); 9 10 }); 11 12 13 14 IAsyncResult asyncRes= delFunc.BeginInvoke(2,3,null,null);//异步调用委托 15 16 //EndInvoke会阻塞当前的线程,直到异步委托指向完成之后,才能继续往下执行。 17 string str =delFunc.EndInvoke(asyncRes); 18 Console.WriteLine(str); 19 20 21 //string str = delFunc(1, 2);同步调用委托 22 //Console.WriteLine(str); 23 24 Console.ReadKey(); 25 }