Threads

  • Thread starter Thread starter C# Learner
  • Start date Start date
C

C# Learner

After a thread has executed and finished, when I try to call its
Start() method again, it throws an exception.

Is it necessary create a new Thread instance every time? Can't I just
re-use the same one?

<relevant parts of the code>

private Thread thread;

public WinForm()
{
thread = new Thread(new ThreadStart(ThreadedCode));
}

private void button1_Click(object sender, System.EventArgs e)
{
thread.Start();
}

private void ThreadedCode()
{
for (int i = 0; i < 10; ++i) {
Text += i;
}
}

</relevant parts of the code>

TIA
 
C# Learner said:
After a thread has executed and finished, when I try to call its
Start() method again, it throws an exception.

Is it necessary create a new Thread instance every time? Can't I just
re-use the same one?

Yes, you need to create a new Thread each time. However, your code is
already not thread-safe - you should only alter the GUI within the
GUI's thread, using Control.Invoke.
 
Back
Top