2009-08-21 69 views
5

我需要幫助創建一個線程,C#的WinForms如何在WinForms中創建線程?

private void button1_Click(object sender, EventArgs e) { 
    Thread t=new Thread(new ThreadStart(Start)).Start(); 
} 

public void Start() { 
    MessageBox.Show("Thread Running"); 
} 

我不斷收到這樣的信息:

Cannot implicitly convert type 'void' to 'System.Threading.Thread 

做什麼的MSDN文檔是沒有好

回答

14

這會工作:

Thread t = new Thread (new ThreadStart (Start)); 
t.Start(); 

而且這會工作,以及:

new Thread (new ThreadStart(Start)).Start(); 

MSDN文檔是好的,正確的,但你這樣做是錯誤的。 :) 你這樣做:

​​

所以,你其實在這裏做的,就是儘量分配由開始()方法(它是無效的),以一個Thread對象返回的對象;因此錯誤消息。

+2

尤其MSDN文檔表明,'開始的返回類型()'是無效... – 2009-08-21 07:05:33

2

嘗試分裂它作爲例如:

private void button1_Click(object sender, EventArgs e) 
{ 
    // create instance of thread, and store it in the t-variable: 
    Thread t = new Thread(new ThreadStart(Start)); 
    // start the thread using the t-variable: 
    t.Start(); 
} 

Thread.Start - 方法返回void(即沒有),所以當你寫

Thread t = something.Start(); 

您要設置Start - 方法,這是無效的結果,到t -variable。這是不可能的,所以你必須把語句分成兩行,如上所述。

2

.NET Framework還提供了一個方便的線程類BackgroundWorker。這很好,因爲您可以使用VisualEditor添加它並設置它的所有屬性。

下面是關於如何使用BackgroundWorker的一個不錯的小教程(含圖片): http://dotnetperls.com/backgroundworker

+1

我我們必須提出這個建議。 BackgroundWorker方法比使用Thread更加初學者友好。它還可以幫助您在UI線程和工作線程之間編組數據。 – 2009-08-21 16:54:06