之前寫一個小型應用程式時遇到需求:新開的執行緒要帶多個參數進去。查了資料、試過幾種寫法後,整理出兩個真正好用的方案。
原理是將要跑的任務連同所需資料都收進同一個類別,透過建構子傳入、用屬性保存,執行緒入口方法再直接讀屬性。這樣做的好處是型別完全明確,編譯期就能檢查,不必來回拆箱。
using System;
using System.Threading;
// ThreadWithState 同時承載「任務」與「參數」
public class ThreadWithState
{
private string boilerplate;
private int value;
public ThreadWithState(string text, int number)
{
boilerplate = text;
value = number;
}
// 無參數、無回傳值,正好符合 ThreadStart 的簽章
public void ThreadProc()
{
Console.WriteLine(boilerplate, value);
}
}
public class Example
{
public static void Main()
{
ThreadWithState tws = new ThreadWithState(
"This report displays the number {0}.", 42);
Thread t = new Thread(new ThreadStart(tws.ThreadProc));
t.Start();
Console.WriteLine("Main thread does some work, then waits.");
t.Join();
Console.WriteLine("Independent task has completed; main thread ends.");
}
}
關鍵那一行是 new Thread(new ThreadStart(tws.ThreadProc)):委派綁的是「已經帶著參數的物件的方法」,參數在建立物件時就固定好了。想傳幾個參數都可以,型別也不受限。
如果不想為此多開一個類別,可以改用 ParameterizedThreadStart,把多個參數打包成一個 object 傳進去,在執行緒內部再還原:
ParameterizedThreadStart parStart = new ParameterizedThreadStart(ThreadMethod); Thread myThread = new Thread(parStart); object o = "hello"; myThread.Start(o); // 參數只能有一個,型別是 object
public void ThreadMethod(object parObject)
{
// 這裡把 parObject 轉回實際型別再使用
}
要傳多個值時,通常會包成自訂類別、tuple 或匿名物件,進到方法後再拆箱。
另外補充一個現代寫法:.NET 4 之後可以直接用 lambda 表達式,把變數靠閉包帶進去,語法最簡潔:
var t = new Thread(() => Console.WriteLine("{0} / {1}", text, number));
t.Start();
而若只是要背景執行一段工作、不需要精細控制 Thread 物件,用 Task.Run 搭配 async/await 會比手動管理 Thread 更省心,也更容易正確處理例外與取消。跨執行緒更新 UI 時,記得回到 UI 執行緒(WinForms 用 Invoke、WPF 用 Dispatcher),這是另一個常見的踩坑點。