There are circumstances that dictate stopping a thread while it is processing. The first thing a user does is to reach for the atomic bomb of an option Thread.Abort() which if called from a different thread interrupts all operations be done. (Note if it is called within the thread itself, it is like throwing an exception and the below problems do not exist.)


Abort() can cause insidious problems within managed code. The cancel will jerk the function pointer out of whatever operations are currently executing. When that happens in the .Net internals it can disrupt specific states and operations that should have been carried out but will be left in an unknown state. When future code, even in other threads, uses that functionality, the improper state will cause problems. when similar processes try to use that functionality it may behave in unpredictable ways.

Anything But Abort

Before using Thread.Abort consider checking a common variable in the worker process which will indicate that things should be stopped. The worker will check the flag and exit immediately. That will be cleaner and will not introduce the problems that Abort may do.

But if You Do

Regardless of whether one intends to call Abort or not, one should handle the abort exception ThreadAbortException. Note in the code below we call ResetAbort to stop the exception from be propagated. In a sense, we could pick up and restart, but since this is a cancel, no sense in fighting it. Here is a snippet to handle the exception properly.

   // Work is done here   
 // Catch this exception if the parent calls thread.abort()
 // So we handle a cancel gracefully.
 catch (ThreadAbortException)
     // We have handled the exception and will simply return without data.
     // Otherwise the abort will be rethrown out of this block.
     // Posibly set a state for any consumers.