views:

191

answers:

3

When a thread is canceled via Thread.Abort() a ThreadAbortException is thrown inside the Thread Thread.Abort was called on. This leads the thread to immediately stop its work and the exception bubbles up the call stack until it leaves the thread's main method. This causes the thread to be aborted.

What are the benefits of an ExceptionHandler for the ThreadAbortException in the threads main method where Thread.ResetAbort() is called, when the thread terminates itself after the catch block due to stepping out its main method?

private void ThreadMainMethod( )
{
    try
    {
     while(runningAllowed = true)
     {
      //Do some work here
     }
    }
    catch ( ThreadAbortException )
    {
     Thread.ResetAbort( );
    }
}
+1  A: 

Probably the only reason you'd do that would be if you were in a great position to decide whether or not you should actually abort.

So perhaps the thread would catch it, check the status of something, and then go back about its work again. Though this does imply that you're basically using the '.abort()' to control the flow of this thread. And that's quite a bad idea. You should communicate with it in another way.

In general, I would think there are not many cases where this is a good idea, and it wouldn't be the advice for any particular pattern or implementation I can think of.

Noon Silk
This is exactly what I meant it to be. I just wanted some clarification, because I#m currently looking at a piece of code where the above statement is used all over the place.
PVitt
+1  A: 

In you particular case it doesn't really make a difference, because the thread will be terminated once the method is done running.

However, in other case you may have a method that runs in an endless loop. In this case, you can shutdown the thread using the ThreadAbortException (I am not saying that you should, but you could). If the thread for some reason determines to continue despite the exception it needs to call ResetAbort to prevent the runtime to automatically rethrow the ThreadAbortException.

Brian Rasmussen
+1  A: 

One scenario I can think of is that you want to take down the thread in a controlled manner. Let's say you have a worker thread that is polling some resource. If the application's main thread invokes Abort on the worker thread, a ThreadAbortException is thrown. You can then catch that exception in start method for the worker thread, call ResetAbort and then finish the method by releasing resource, closing open files/connections and so on:

public void ThreadStarter()
{
    try
    {
        RunWorkerLoop();
    }
    catch (ThreadAbortException)
    {
        Thread.ResetAbort();
    }

    // clean up and end gracefully

}
Fredrik Mörk