2012-01-14 87 views

回答

36

ThreadStart不僅期望無效的方法,它也希望他們不要拿任何參數!您可以將其包裝在一個lambda,一個匿名委託或一個命名的靜態函數中。

這裏是做這件事的一種方法:

string res = null; 
Thread newThread = new Thread(() => {res = sayHello("world!");}); 
newThread.Start(); 
newThread.Join(1000); 
Console.Writeline(res); 

這裏是另一個語法:

Thread newThread = new Thread(delegate() {sayHello("world!");}); 
newThread.Start(); 

第三個語法(以命名函數)是最無聊:

// Define a "wrapper" function 
static void WrapSayHello() { 
    sayHello("world!); 
} 

// Call it from some other place 
Thread newThread = new Thread(WrapSayHello); 
newThread.Start(); 
+0

它一直對我有幫助。謝謝。 – 2012-01-14 04:35:16

+0

我無法獲得返回值。如何使用返回值? – 2012-01-14 04:38:13

+1

[ParameterizedThreadStart Delegate](http://msdn.microsoft.com/zh-cn/library/system.threading.parameterizedthreadstart.aspx) – 2012-01-14 04:41:54

3

您應該爲此使用Task

0

如果你可以使用線程的任何方法,嘗試BackgroundWorker

BackgroundWorker bw = new BackgroundWorker(); 
public Form1() 
{ 
    InitializeComponent(); 

    bw.DoWork += bw_DoWork; 
    bw.RunWorkerCompleted += bw_RunWorkerCompleted; 
    bw.RunWorkerAsync("MyName"); 
} 

void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 
{ 
    Text = (string)e.Result; 
} 

void bw_DoWork(object sender, DoWorkEventArgs e) 
{ 
    string name = (string)e.Argument; 
    e.Result = "Hello ," + name; 
}