這幾天,看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