1.3 在当前线程中启动线程T,只要T在执行就执行任务R,最后获取T的返回值
01 [STAThread] 02 static void Main() 03 { 04 AsyncFuncDelegate caller = new AsyncFuncDelegate(Func); 05 Console.WriteLine("Input number please..."); 06 IAsyncResult result = caller.BeginInvoke(Convert.ToInt32(Console.ReadLine()), null, null); 07 while (!result.IsCompleted) 08 { 09 Thread.Sleep(1000); 10 Console.Write(">"); 11 } 12 Console.WriteLine(""); 13 Console.WriteLine("Implement other task2"); 14 Console.WriteLine("Get user's input"); 15 Console.WriteLine(caller.EndInvoke(result)); 16 Console.ReadLine(); 17 } |
输出结果如下:
Func start to run ... >>>>>Func end to run > Implement other task2 Get user's input 23 |
2 不需要在当前线程中获取返回值,但是仍然需要对返回值做处理
01 using System; 02 using System.Collections.Generic; 03 using System.Linq; 04 using System.Windows.Forms; 05 using System.Threading; 06 using System.Runtime.Remoting.Messaging; 07 namespace FirstWF 08 { 09 static class Program 10 { 11 /// <summary> 12 /// The main entry point for the application. 13 /// </summary> 14 [STAThread] 15 static void Main() 16 { 17 AsyncFuncDelegate caller = new AsyncFuncDelegate(Func); 18 Console.WriteLine("Input number please..."); 19 caller.BeginInvoke(Convert.ToInt32(Console.ReadLine()), new AsyncCallback(CallBackFunc), "Message from Main thread."); 20 Console.WriteLine("Main thread ends"); 21 Console.ReadLine(); 22 } 23 delegate string AsyncFuncDelegate(int userInput); 24 static string Func(int userInput) 25 { 26 Console.WriteLine("Func start to run"); 27 Console.WriteLine("..."); 28 Thread.Sleep(5000); 29 Console.WriteLine("Func end to run"); 30 return userInput.ToString(); 31 } 32 static void CallBackFunc(IAsyncResult ar) 33 { 34 AsyncResult result = ar as AsyncResult; 35 string inputMessage = result.AsyncState as string; 36 AsyncFuncDelegate caller = result.AsyncDelegate as AsyncFuncDelegate; 37 Console.WriteLine("call back starts"); 38 Console.WriteLine(inputMessage); 39 Console.WriteLine("The input number is : " + caller.EndInvoke(ar)); 40 Console.WriteLine("call back ends"); 41 } 42 } 43 } |
输出结果如下:
Input number please... |