Share via


Destroying Threads

The Thread.Abort method is used to stop a logical thread permanently. When you call Abort, the common language runtime throws a ThreadAbortException, which the thread can catch. For more information, see Thread.Abort.

Because Thread.Abort does not cause the thread to abort immediately, you must call Thread.Join to wait on the thread if you need to be sure the thread is stopped. Join is a blocking call that does not return until the thread has actually stopped executing. Once a thread is aborted, it cannot be restarted.

You can also call Thread.Join and pass a time-out period. If the thread dies before the time out has elapsed, the call returns true. Otherwise, if the time expires before the thread dies, the call returns false. Threads that are waiting on a call to Thread.Join can be interrupted by other threads that call Thread.Interrupt.

ThreadAbortException

A ThreadAbortException can occur anywhere in managed code. However, it occurs only if a sufficiently privileged thread calls Thread.Abort or AppDomain.Unload (which itself uses Thread.Abort). The best way to handle a ThreadAbortException is to have adequate finally or catch clauses so that you maintain consistent state if you must back out. The privileged code that provokes the ThreadAbortException will catch it and reset it if necessary.

The following C# code example is incorrect.

try {
   // Insert code that throws an exception.
} catch (Exception e) {
   // Insert the first part of backout code here.
   // < --- ThreadAbortException thrown by the system < -- 
}
...// additional backout code here.

To make the preceding code work, you must move the additional backout code into the catch block, or put it into a finally block. This is because a ThreadAbortException will be implicitly rethrown by the system after entering the catch block, regardless of what you do with it in that block. Another way of saying this is that although you can catch a ThreadAbortException, you cannot suppress it — it is automatically rethrown as necessary. The only way to suppress one of these exceptions explicitly is to call Thread.ResetAbort, and this requires the appropriate privilege. You should only do this if you are the one who provoked the ThreadAbortException in the first place.

See Also

Using Threads and Threading | ThreadAbortException | Thread Class