在 .NET 執行環境中,程式啟動時會自動分配一條主線程(由 Main() 方法啟動),垃圾回收等後台工作也在獨立線程中悄然進行。雖然單線程模型簡單,但面對「使用者輸入需即時回應」與「大量運算/繪圖耗時」並存的場景,單一線程勢必造成介面卡頓。此時引入多線程,讓耗時任務移至背景執行,主線程專注處理 UI 互動,便能顯著提升應用程式的流暢度與回應速度。
System.Threading 命名空間提供了豐富的多線程支援,其中 Thread 類別 是創建、控制線程、設定優先權與取得狀態的核心。以下整理其最常用的方法與屬性:
WaitSleepJoin 狀態的線程,會拋出 ThreadInterruptedException。ThreadAbortException。注意:被中止的線程無法重新啟動;呼叫 Abort() 後應配合 Join() 確認終止。Highest, AboveNormal, Normal, BelowNormal, Lowest)。高優先權線程獲得更多 CPU 時間片。Unstarted, Running, WaitSleepJoin, Suspended, AbortRequested, Stopped 等,可組合)。線程從建立(Unstarted)→ Start() → Running。若呼叫 Sleep()、Join() 或等待鎖則進入 WaitSleepJoin;被 Suspend() 則為 Suspended;收到 Abort() 進入 AbortRequested,最終轉為 Stopped。一個線程可同時處於多種狀態(如 WaitSleepJoin | AbortRequested)。
using System;
using System.Threading;
namespace LearnThreads
{
class ThreadApp
{
public static void FirstThread()
{
Console.WriteLine("First thread created");
Thread current = Thread.CurrentThread;
string details = $"Thread Name: {current.Name}\r\nThread State: {current.ThreadState}\r\nPriority: {current.Priority}";
Console.WriteLine($"Thread details: {details}");
Console.WriteLine("First thread terminated");
}
public static void Main()
{
ThreadStart starter = new ThreadStart(FirstThread);
Console.WriteLine("Creating first thread...");
Thread t = new Thread(starter);
t.Name = "FirstThread";
t.Start(); // 啟動線程
}
}
}
此範例展示以 ThreadStart 委派包裝方法,實例化 Thread 並設定名稱後啟動。啟動瞬間線程進入 Running 狀態,執行 FirstThread 邏輯。
作業系統依優先權分配 CPU 時間:高優先權線程優先執行;同優先權則輪轉。新建線程預設為 Normal。合理設定優先權可避免低優先權任務佔用資源導致高優先權任務延遲,但切勿過度依賴優先權解決同步問題,應使用鎖、訊號等同步機制。
本章詳細解析了 Thread 類別的核心方法、屬性、狀態流轉與優先權機制,並提供完整建立線程範例。System.Threading 還包含線程同步(lock, Monitor, Mutex)、執行緒池(ThreadPool)、非同步模式(async/await)等進階主題,將於後續章節深入探討。