2009-08-21 59 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