Restarting a thread in .NET (using C#)

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.

Leave a Comment