.Net异步处理温习2011-01-12 博客园 Virtual Coder这几天,看WF本质论,里面提到了.net的异步处理。由于里面使用的是代码片段,所以有点看不懂。于是下定决心,温习一下.net中的异步处理。使用C#在.net开发已经有5年了,最初使用.net中的异步处理大约是在4年前。当时,只是为了实现要求的功能,没有详细研究。这也难怪看WF时会头晕(基础不牢的后果呀)。首先,我们分析一下异步处理的环境1. 需要在当前线程中获取返回值2. 不需要在当前线程中获取返回值,但是仍然需要对返回值做处理对于第1中情况,还可以继续细分1. 在当前线程中启动线程T,然后继续执行当前线程中的其它任务,最后在当前线程中获取T的返回值2. 在当前线程中启动线程T,然后继续执行当前线程中的其它任务R1,等待T执行完成,当T执行完成后,继续执行当前线程中的其它任务R2,最后获取T的返回值3. 在当前线程中启动线程T,只要T在执行就执行任务R,最后获取T的返回值下面,我将一一给出例子:1.1 在当前线程中启动线程T,然后继续执行当前线程中的其它任务,最后在当前线程中获取T的返回值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 IAsyncResult result = caller.BeginInvoke(Convert.ToInt32(Console.ReadLine()), null, null); 20 Console.WriteLine("Implement other tasks"); 21 Thread.Sleep(7000); 22 Console.WriteLine("Implement other tasks end ..."); 23 Console.WriteLine("Get user"s input"); 24 Console.WriteLine(caller.EndInvoke(result)); 25 Console.ReadLine(); 26 } 27 delegate string AsyncFuncDelegate(int userInput); 28 static string Func(int userInput) 29 { 30 Console.WriteLine("Func start to run"); 31 Console.WriteLine("..."); 32 Thread.Sleep(5000); 33 Console.WriteLine("Func end to run"); 34 return userInput.ToString(); 35 } 36 } 37 }输出结果如下:Implement other tasks Func start to run ... Func end to run Implement other tasks end ... Get user"s input 56