主要有兩種方式,第一種為使用 ParameterizedThreadStart,但是這不是一個安全的方式。第二種方法是將要交給執行緒執行的方法與參數封裝到類別裡頭去,建立該類別的 Instance 之後就可以交給執行緒去執行,以下為 sample code... (另外要注意的是 Threading.Join() 的使用)
using System;
using System.Threading;
//ThreadWithState 類別裡包含執行任務的方法
public class ThreadWithState {
//要用到的屬性,也就是我們要傳遞的參數
private string boilerplate;
private int value;
//包含參數的 Constructor
public ThreadWithState(string text, int number)
{
boilerplate = text;
value = number;
}
//要丟給執行緒執行的方法,無 return value 就是為了能讓ThreadStart來呼叫
public void ThreadProc()
{
//這裡就是要執行的任務, 只顯示一下傳入的參數
Console.WriteLine(boilerplate, value);
}
}
//Main entrance
public class Example {
public static void Main()
{
//實例化ThreadWithState類別,為執行緒提供參數
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.");
}
}