C# 多線程與非同步區別

來源:互聯網
上載者:User

隨著擁有多個硬線程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使用了另外的線程來執行目標方法。到底是不是這樣呢?讓我們來用一段代碼證明一下吧。

using System;
using System.Threading;

namespace AsyncDelegateDemo
{
  delegate void AsyncFoo(int i);
  class Program
  {
    /// <summary>
    /// 輸出當前線程的資訊
    /// </summary>
   /// <param name="name">方法名稱</param>

    static void PrintCurrThreadInfo(string name)
    {
      Console.WriteLine("Thread Id of " + name+ " is: " + Thread.CurrentThread.ManagedThreadId+ ", current thread is "
      + (Thread.CurrentThread.IsThreadPoolThread ? "" : "not ")
      + "thread pool thread.");
    }

    /// <summary>
    /// 測試方法,Sleep一定時間
    /// </summary>
    /// <param name="i">Sleep的時間</param>
    static void Foo(int i)
    {
       PrintCurrThreadInfo("Foo()");
       Thread.Sleep(i);
    }

    /// <summary>
    /// 投遞一個非同步呼叫
    /// </summary>
    static void PostAsync()
    {
      AsyncFoo caller = new AsyncFoo(Foo);
      caller.BeginInvoke(1000, new AsyncCallback(FooCallBack), caller);
    }

    static void Main(string[] args)
    {
      PrintCurrThreadInfo("Main()");
      for(int i = 0; i < 10 ; i++)
      {
         PostAsync();
      }
      Console.ReadLine();
    }

    static void FooCallBack(IAsyncResult ar)
    {
      PrintCurrThreadInfo("FooCallBack()");
      AsyncFoo caller = (AsyncFoo) ar.AsyncState;
      caller.EndInvoke(ar);
    }
  }

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

Thread Id of Main() is: 1, current thread is not thread pool thread.

Thread Id of Foo() is: 3, current thread is thread pool thread.

Thread Id of FooCallBack() is: 3, current thread is thread pool thread.

Thread Id of Foo() is: 3, current thread is thread pool thread.

Thread Id of Foo() is: 4, current thread is thread pool thread.

Thread Id of Foo() is: 5, current thread is thread pool thread.

Thread Id of FooCallBack() is: 3, current thread is thread pool thread.

Thread Id of Foo() is: 3, current thread is thread pool thread.

Thread Id of FooCallBack() is: 4, current thread is thread pool thread.

Thread Id of Foo() is: 4, current thread is thread pool thread.

Thread Id of Foo() is: 6, current thread is thread pool thread.

Thread Id of FooCallBack() is: 5, current thread is thread pool thread.

Thread Id of Foo() is: 5, current thread is thread pool thread.

Thread Id of Foo() is: 7, current thread is thread pool thread.

Thread Id of FooCallBack() is: 3, current thread is thread pool thread.

Thread Id of Foo() is: 3, current thread is thread pool thread.

Thread Id of FooCallBack() is: 4, current thread is thread pool thread.

Thread Id of FooCallBack() is: 6, current thread is thread pool thread.

Thread Id of FooCallBack() is: 5, current thread is thread pool thread.

Thread Id of FooCallBack() is: 7, current thread is thread pool thread.

Thread Id of FooCallBack() is: 3, current thread is thread pool thread. 


從輸出可以看出,.net使用delegate來"自動"產生的非同步呼叫是使用了另外的線程(而且是線程池線程)。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.