C# 中的執行緒


執行緒定義為程式的執行路徑。每個執行緒定義一個獨特的控制流程。如果你的應用程式涉及複雜且耗時的操作,那麼設定不同的執行路徑或執行緒通常會有所幫助,每個執行緒執行特定的作業。

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

以下是執行緒生命週期中的各種狀態 −

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

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

  • 不可執行狀態 - 執行緒不可執行,當

    • 已呼叫睡眠方法
    • 已呼叫等待方法
    • 被 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.