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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

threading 2
Stopping a listening thread 2
Thread GC collection 6
timer/threading 10
Help with thread 1
GUI Thread - Is cross-thread operation really bad? 19
.NET Threading Question 17
Threading 8

Back
Top