C# 中的執行緒


執行緒定義為程式的執行路徑。每個執行緒定義一個獨特的控制流。如果你的應用程式包含複雜且耗時的操作,則通常可以設定不同的執行路徑或執行緒,每個執行緒執行特定的作業。

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

以下是執行緒生命週期中的各個狀態 -

  • 未啟動狀態 - 是指建立了執行緒的例項但未呼叫 Start 方法的情況。

  • 就緒狀態 - 是指執行緒已準備好執行並等待 CPU 週期的情況。

  • 不可執行狀態 - 當

    • 呼叫了 Sleep 方法時
    • 呼叫了 Wait 方法時
    • 被 I/O 操作阻塞時執行緒不可執行。
  • 死亡狀態 - 是指執行緒完成執行或被中止的情況。

以下是一個示例,顯示如何建立執行緒 -

示例

 線上演示

using System;
using System.Threading;

namespace Demo {
   class Program {
      public static void ThreadFunc() {
         Console.WriteLine("Child thread starts");
      }

      static void Main(string[] args) {
         ThreadStart childref = new ThreadStart(ThreadFunc);
         Console.WriteLine("In Main: Creating the Child thread");
         Thread childThread = new Thread(childref);
         childThread.Start();
         Console.ReadKey();
      }
   }
}

輸出

In Main: Creating the Child thread
Child thread starts

更新時間: 20-6-2020

569 次瀏覽

開啟您的 事業

完成課程,獲得認證

開始
廣告
© . All rights reserved.