Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restarting a thread in .NET (using C#)

I'm looking for a way to restart a thread that has been stopped by Abort()..

public partial class MyProgram : Form
{
  private Thread MyThread = new Thread(MyFunction);
  private System.Windows.Forms.Button startStopBtn = new System.Windows.Forms.Button();
  public MyProgram()
  {
    MyThread.Start();
    startStopBtn += new EventHandler(doStop);
    startStopBtn.Text = "Stop";
  }
  private static void MyFunction()
  {
    // do something
  }
  private void doStop(object sender, EventArgs e)
  {
    MyThread.Abort();
    startStopBtn -= new EventHandler(doStop);
    startStopBtn += new EventHandler(doStart);
    startStopBtn.Text = "Start";
  }
  private void doStart(object sender, EventArgs e)
  {
    MyThread.Start(); // << Error returned when clicking the button for 2nd time
    startStopBtn -= new EventHandler(doStart);
    startStopBtn += new EventHandler(doStop);
    startStopBtn.Text = "Stop";
  }
}

Any idea?

like image 931
Yana D. Nugraha Avatar asked Jun 28 '09 13:06

Yana D. Nugraha


People also ask

How do you restart a thread?

Calling the start() function on a terminated thread will result in a RuntimeError indicating that threads can only be started once. Instead, to restart a thread in Python, you must create a new instance of the thread with the same configuration and then call the start() function.

Can we restart the thread?

Once a thread enters dead state it cannot be restarted.

What method do you call to start a thread in C#?

The Thread constructor takes a ThreadStart delegate as a parameter and creates a new thread. The parameter of the ThreadStart is the method that is executed by the new thread. Once a thread it created, it needs to call the Start method to actually start the thread.

How do I stop and restart a thread?

Once a thread stops you cannot restart it. However, there is nothing stopping you from creating and starting a new thread. Option 1: Create a new thread rather than trying to restart. Option 2: Instead of letting the thread stop, have it wait and then when it receives notification you can allow it to do work again.


2 Answers

Simply add MyThread = new Thread(MyFunction) before calling MyThread.Start() in doStart(). Do not create the thread outside of your methods, the space there is thought for declarations.

Please note that killing a thread with thread.Abort() can be very dangerous, as it might cause unexpected behavior or might not correctly dispose resources owned by the thread. You should try to accomplish clean multi threading, like Groo described in his answer.

like image 38
Emiswelt Avatar answered Sep 19 '22 03:09

Emiswelt


Once you have aborted your thread, you cannot start it again.

But your actual problem is that you are aborting your thread. You should never use Thread.Abort().

If your thread should be paused and continued several times, you should consider using other mechanisms (like AutoResetEvent, for example).

[EDIT]

The simplest solution to abort a thread, as mentioned by Ian Griffiths in the link above, is:

The approach I always recommend is dead simple. Have a volatile bool field that is visible both to your worker thread and your UI thread. If the user clicks cancel, set this flag. Meanwhile, on your worker thread, test the flag from time to time. If you see it get set, stop what you're doing.

The only thing that you need to do to make it work properly, is to rearrange your background method so that it runs in a loop - so that you can periodically check if your flag has been set by a different thread.

If you need to have pause and resume functionality for the same worker thread, instead of the simple volatile bool flag approach, you could go for a slightly more complex approach, a synchronizing construct such as AutoResetEvent. These classes also provide a way to put the worker thread to sleep for a specified (or indefinite) amount of time between signals from the non-worker thread.

This thread contains a concrete example with Start, Pause, Resume and Stop methods. Note how Brannon's example never aborts the thread. It only fires an event, and then waits until the thread finishes gracefully.

like image 195
Groo Avatar answered Sep 19 '22 03:09

Groo