1 //定義一個委托 2 static Func delFunc = (a, b) => 3 { 4 Console.WriteLine("委托線程:" + Thread.CurrentThread.ManagedThreadId); 5 return (a + b).ToString(); 6 }... ...
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 }