Reputation: 20032
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
Upvotes: 8
Views: 17971
Reputation: 3740
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
Upvotes: 4
Reputation: 6340
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.
Upvotes: 2
Reputation: 56984
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.
Upvotes: 18