1. 程式人生 > >c#基礎知識---多執行緒

c#基礎知識---多執行緒

執行緒 被定義為程式的執行路徑。每個執行緒都定義了一個獨特的控制流。如果您的應用程式涉及到複雜的和耗時的操作,那麼設定不同的執行緒執行路徑往往是有益的,每個執行緒執行特定的工作。

執行緒是輕量級程序。一個使用執行緒的常見例項是現代作業系統中並行程式設計的實現。使用執行緒節省了 CPU 週期的浪費,同時提高了應用程式的效率。

到目前為止我們編寫的程式是一個單執行緒作為應用程式的執行例項的單一的過程執行的。但是,這樣子應用程式同時只能執行一個任務。為了同時執行多個任務,它可以被劃分為更小的執行緒。

執行緒生命週期

執行緒生命週期開始於 System.Threading.Thread 類的物件被建立時,結束於執行緒被終止或完成執行時。

下面列出了執行緒生命週期中的各種狀態:

  • 未啟動狀態:當執行緒例項被建立但 Start 方法未被呼叫時的狀況。
  • 就緒狀態:當執行緒準備好執行並等待 CPU 週期時的狀況。
  • 不可執行狀態:下面的幾種情況下執行緒是不可執行的:
    • 已經呼叫 Sleep 方法
    • 已經呼叫 Wait 方法
    • 通過 I/O 操作阻塞
  • 死亡狀態:當執行緒已完成執行或已中止時的狀況。

主執行緒

在 C# 中,System.Threading.Thread 類用於執行緒的工作。它允許建立並訪問多執行緒應用程式中的單個執行緒。程序中第一個被執行的執行緒稱為主執行緒

當 C# 程式開始執行時,主執行緒自動建立。使用 Thread

 類建立的執行緒被主執行緒的子執行緒呼叫。您可以使用 Thread 類的 CurrentThread 屬性訪問執行緒。

下面的程式演示了主執行緒的執行:

usingSystem;usingSystem.Threading;namespaceMultithreadingApplication{classMainThreadProgram{staticvoidMain(string[] args){Thread th =Thread.CurrentThread;
            th.Name="MainThread";Console.WriteLine("This is {0}", th
.Name);Console.ReadKey();}}}

當上面的程式碼被編譯和執行時,它會產生下列結果:

ThisisMainThread

建立執行緒

執行緒是通過擴充套件 Thread 類建立的。擴充套件的 Thread 類呼叫 Start() 方法來開始子執行緒的執行。

下面的程式演示了這個概念:

usingSystem;usingSystem.Threading;namespaceMultithreadingApplication{classThreadCreationProgram{publicstaticvoidCallToChildThread(){Console.WriteLine("Child thread starts");}staticvoidMain(string[] args){ThreadStart childref =newThreadStart(CallToChildThread);Console.WriteLine("In Main: Creating the Child thread");Thread childThread =newThread(childref);
            childThread.Start();Console.ReadKey();}}}

當上面的程式碼被編譯和執行時,它會產生下列結果:

InMain:Creating the Child thread
Child thread starts

管理執行緒

Thread 類提供了各種管理執行緒的方法。

下面的例項演示了 sleep() 方法的使用,用於在一個特定的時間暫停執行緒。

usingSystem;usingSystem.Threading;namespaceMultithreadingApplication{classThreadCreationProgram{publicstaticvoidCallToChildThread(){Console.WriteLine("Child thread starts");// 執行緒暫停 5000 毫秒int sleepfor =5000;Console.WriteLine("Child Thread Paused for {0} seconds", 
                              sleepfor /1000);Thread.Sleep(sleepfor);Console.WriteLine("Child thread resumes");}staticvoidMain(string[] args){ThreadStart childref =newThreadStart(CallToChildThread);Console.WriteLine("In Main: Creating the Child thread");Thread childThread =newThread(childref);
            childThread.Start();Console.ReadKey();}}}

當上面的程式碼被編譯和執行時,它會產生下列結果:

InMain:Creating the Child thread
Child thread starts
ChildThreadPausedfor5 seconds
Child thread resumes

銷燬執行緒

Abort() 方法用於銷燬執行緒。

通過丟擲 threadabortexception 在執行時中止執行緒。這個異常不能被捕獲,如果有 finally 塊,控制會被送至 finally 塊。

下面的程式說明了這點:

usingSystem;usingSystem.Threading;namespaceMultithreadingApplication{classThreadCreationProgram{publicstaticvoidCallToChildThread(){try{Console.WriteLine("Child thread starts");// 計數到 10for(int counter =0; counter <=10; counter++){Thread.Sleep(500);Console.WriteLine(counter);}Console.WriteLine("Child Thread Completed");}catch(ThreadAbortException e){Console.WriteLine("Thread Abort Exception");}finally{Console.WriteLine("Couldn't catch the Thread Exception");}}staticvoidMain(string[] args){ThreadStart childref =newThreadStart(CallToChildThread);Console.WriteLine("In Main: Creating the Child thread");Thread childThread =newThread(childref);
            childThread.Start();// 停止主執行緒一段時間Thread.Sleep(2000);// 現在中止子執行緒Console.WriteLine("In Main: Aborting the Child thread");
            childThread.Abort();Console.ReadKey();}}}

當上面的程式碼被編譯和執行時,它會產生下列結果:

InMain:Creating the Child thread
Child thread starts
012InMain:Aborting the Child thread
ThreadAbortExceptionCouldn't catch the Thread Exception