views:

252

answers:

3

I need help in creating a thread, C# winforms

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

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

I keep getting this message:

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

what to do the msdn documentation is no good

+2  A: 

Try splitting it up as such:

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();
}

The Thread.Start-method returns void (i.e. nothing), so when you write

Thread t = something.Start();

you are trying to set the result of the Start-method, which is void, to the t-variable. This is not possible, and so you have to split the statement into two lines as specified above.

Bernhof
+7  A: 

This would work:

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

And this would work as well:

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

The MSDN documentation is good and correct, but you're doing it wrong. :) You do this:

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

So, what you do here in fact, is try to assign the object that is returned by the Start() method (which is void) to a Thread object; hence the error message.

Frederik Gheysels
In particular, the MSDN documentation indicates that the return type of `Start()` is void...
Jon Skeet
+1  A: 

The .NET framework also provides a handy thread class BackgroundWorker. It is nice because you can add it using the VisualEditor and setup all of it's properties.

Here is a nice small tutorial (with images) on how to use the backgroundworker: http://dotnetperls.com/backgroundworker

Setheron
I'd have to second that suggestion. The BackgroundWorker approach is much more beginner friendly than using Thread. It also helps you marshal data between the UI thread and the worker thread.
Allon Guralnek