c# 多線程與異步調用


  異步操作的本質

  在方法調用前為異步方法指定一個回調函數,方法調用后被線程池中的一個線程接管,執行該方法。主線程立即返回,繼續執行其他工作或響應用戶請求。如果異步方法執行完    畢,回調函數被自動執行,以處理異步方法的調用結果。 如何實現異步方法呢?C#通過異步委托調用BeginInvoke和EndInvoke方法來實現異步方法。

  BeginInvoke方法原型: IAsyncResult BeginInvoke(......, AsyncCallback callback, object o); ......表示異步委托中定義的參數列表。 AsyncCallback參數是一個用於  回調函數的委托,它的原型為: public delegate void AsyncCallback(IAsyncResult ar)。其中IAsyncResult參數用於包裝異步方法的執行結果。 Object參數用於在主線程與回調函數間傳遞一些附加信息,如同步信息。

EndInvoke方法原型: xxx EndInvoke(IAsyncResult result); xxx表示異步委托原型中定義的返回數據類型,IAsyncResult用於包裝異步方法的執行結果。

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

  異步操作的優缺點

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

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

  適用范圍

  在了解了線程與異步操作各自的優缺點之后,我們可以來探討一下線程和異步的合理用途。我認為:當需要執行I/O操作時,使用異步操作比使用線程+同步I/O操作更合適。I/O操作不僅包括了直接的文件、網絡的讀寫,還包括數據庫操作、Web Service、HttpRequest以及.Net Remoting等跨進程的調用。
  而線程的適用范圍則是那種需要長時間CPU運算的場合,例如耗時較長的圖形處理和算法執行。但是往往由於使用線程編程的簡單和符合習慣,所以很多朋友往往會使用線程來執行耗時較長的I/O操作。這樣在只有少數幾個並發操作的時候還無傷大雅,如果需要處理大量的並發操作時就不合適了。

下面看個異步調用的實例:

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.  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM