C# 多線程與異步操作實現的探討

原文鏈接:http://dev.firnow.com/course/4_webprogram/asp.net/netjs/2008530/118075.html

 

隨着擁有多個硬線程CPU(超線程、雙核)的普及,多線程和異步操作等併發程序設計方法也受到了更多的關注和討論。本文主要是想與園中各位高手一同探討一下如何使用併發來最大化程序的性能。

  多線程和異步操作的異同

  多線程和異步操作兩者都可以達到避免調用線程阻塞的目的,從而提高軟件的可響應性。甚至有些時候我們就認爲多線程和異步操作是等同的概念。但是,多線程和異步操作還是有一些區別的。而這些區別造成了使用多線程和異步操作的時機的區別。

  異步操作的本質

   所有的程序最終都會由計算機硬件來執行,所以爲了更好的理解異步操作的本質,我們有必要了解一下它的硬件基礎。 熟悉電腦硬件的朋友肯定對DMA這個詞不陌生,硬盤、光驅的技術規格中都有明確DMA的模式指標,其實網卡、聲卡、顯卡也是有DMA功能的。DMA就是直 接內存訪問的意思,也就是說,擁有DMA功能的硬件在和內存進行數據交換的時候可以不消耗CPU資源。只要CPU在發起數據傳輸時發送一個指令,硬件就開 始自己和內存交換數據,在傳輸完成之後硬件會觸發一箇中斷來通知操作完成。這些無須消耗CPU時間的I/O操作正是異步操作的硬件基礎。所以即使在DOS 這樣的單進程(而且無線程概念)系統中也同樣可以發起異步的DMA操作。

  線程的本質

  線程不是一個計算機硬件的功能,而是操作系統提供的一種邏輯功能,線程本質上是進程中一段併發運行的代碼,所以線程需要操作系統投入CPU資源來運行和調度。

  異步操作的優缺點

   因爲異步操作無須額外的線程負擔,並且使用回調的方式進行處理,在設計良好的情況下,處理函數可以不必使用共享變量(即使無法完全不用,最起碼可以減少 共享變量的數量),減少了死鎖的可能。當然異步操作也並非完美無暇。編寫異步操作的複雜程度較高,程序主要使用回調方式進行處理,與普通人的思維方式有些 初入,而且難以調試。

  多線程的優缺點

  多線程的優點很明顯,線程中的處理程序依然是順序執行,符合普通人的思維習慣,所以編程簡單。但是多線程的缺點也同樣明顯,線程的使用(濫用)會給系統帶來上下文切換的額外負擔。並且線程間的共享變量可能造成死鎖的出現。

  適用範圍

   在瞭解了線程與異步操作各自的優缺點之後,我們可以來探討一下線程和異步的合理用途。我認爲:當需要執行I/O操作時,使用異步操作比使用線程+同步 I/O操作更合適。I/O操作不僅包括了直接的文件、網絡的讀寫,還包括數據庫操作、Web Service、HttpRequest以及.net Remoting等跨進程的調用。

  而線程的適用範圍則是那種需要長時間CPU運算的場合,例如耗時較長的圖形處理和算法執行。但是往 往由於使用線程編程的簡單和符合習慣,所以很多朋友往往會使用線程來執行耗時較長的I/O操作。這樣在只有少數幾個併發操作的時候還無傷大雅,如果需要處 理大量的併發操作時就不合適了。

  實例研究

  說了那麼理論上的東西,可能有些兄弟早就不耐煩了,現在我們來研究幾個實際的異步操作例子吧。

  實例1:由delegate產生的異步方法到底是怎麼回事?

  大家可能都知道,使用delegate可以“自動”使一個方法可以進行異步的調用。從直覺上來說,我覺得是由編譯器或者CLR使用了另外的線程來執行目標方法。到底是不是這樣呢?讓我們來用一段代碼證明一下吧。

01 using System;
02 using System.Threading;
03  
04 namespace AsyncDelegateDemo
05 {
06   delegate void AsyncFoo(int i);
07   class Program
08   {
09     /// <summary>
10     /// 輸出當前線程的信息
11     /// </summary>
12    /// <param name="name">方法名稱</param>
13  
14     static void PrintCurrThreadInfo(string name)
15     {
16       Console.WriteLine("Thread Id of " + name+ " is: " + Thread.CurrentThread.ManagedThreadId+ ", current thread is "
17       + (Thread.CurrentThread.IsThreadPoolThread ? "" "not ")
18       "thread pool thread.");
19     }
20  
21     /// <summary>
22     /// 測試方法,Sleep一定時間
23     /// </summary>
24     /// <param name="i">Sleep的時間</param>
25     static void Foo(int i)
26     {
27        PrintCurrThreadInfo("Foo()");
28        Thread.Sleep(i);
29     }
30  
31     /// <summary>
32     /// 投遞一個異步調用
33     /// </summary>
34     static void PostAsync()
35     {
36       AsyncFoo caller = new AsyncFoo(Foo);
37       caller.BeginInvoke(1000, new AsyncCallback(FooCallBack), caller);
38     }
39  
40     static void Main(string[] args)
41     {
42       PrintCurrThreadInfo("Main()");
43       for(int i = 0; i < 10 ; i++)
44       {
45          PostAsync();
46       }
47       Console.ReadLine();
48     }
49  
50     static void FooCallBack(IAsyncResult ar)
51     {
52       PrintCurrThreadInfo("FooCallBack()");
53       AsyncFoo caller = (AsyncFoo) ar.AsyncState;
54       caller.EndInvoke(ar);
55     }
56   }
57 }

 

 

這段代碼代碼的輸出如下:

01 Thread Id of Main() is: 1, current thread is not thread pool thread.
02  
03 Thread Id of Foo() is: 3, current thread is thread pool thread.
04  
05 Thread Id of FooCallBack() is: 3, current thread is thread pool thread.
06  
07 Thread Id of Foo() is: 3, current thread is thread pool thread.
08  
09 Thread Id of Foo() is: 4, current thread is thread pool thread.
10  
11 Thread Id of Foo() is: 5, current thread is thread pool thread.
12  
13 Thread Id of FooCallBack() is: 3, current thread is thread pool thread.
14  
15 Thread Id of Foo() is: 3, current thread is thread pool thread.
16  
17 Thread Id of FooCallBack() is: 4, current thread is thread pool thread.
18  
19 Thread Id of Foo() is: 4, current thread is thread pool thread.
20  
21 Thread Id of Foo() is: 6, current thread is thread pool thread.
22  
23 Thread Id of FooCallBack() is: 5, current thread is thread pool thread.
24  
25 Thread Id of Foo() is: 5, current thread is thread pool thread.
26  
27 Thread Id of Foo() is: 7, current thread is thread pool thread.
28  
29 Thread Id of FooCallBack() is: 3, current thread is thread pool thread.
30  
31 Thread Id of Foo() is: 3, current thread is thread pool thread.
32  
33 Thread Id of FooCallBack() is: 4, current thread is thread pool thread.
34  
35 Thread Id of FooCallBack() is: 6, current thread is thread pool thread.
36  
37 Thread Id of FooCallBack() is: 5, current thread is thread pool thread.
38  
39 Thread Id of FooCallBack() is: 7, current thread is thread pool thread.
40  
41 Thread Id of FooCallBack() is: 3, current thread is thread pool thread.

 

 


從輸出可以看出,.net使用delegate來“自動”生成的異步調用是使用了另外的線程(而且是線程池線程)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章