Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a thread in WinForms?

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

like image 248
Moon Avatar asked Aug 21 '09 06:08

Moon


3 Answers

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.

like image 190
Frederik Gheysels Avatar answered Oct 21 '22 14:10

Frederik Gheysels


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

like image 41
Setheron Avatar answered Oct 21 '22 15:10

Setheron


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.

like image 25
bernhof Avatar answered Oct 21 '22 13:10

bernhof