.Net非同步處理溫習

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.