Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefits of Thread.ResetAbort

When a thread is canceled via Thread.Abort(), a ThreadAbortException is thrown inside the Thread on which 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 anyway 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( );
    }
}
like image 207
PVitt Avatar asked Aug 27 '09 07:08

PVitt


2 Answers

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

}
like image 119
Fredrik Mörk Avatar answered Oct 20 '22 01:10

Fredrik Mörk


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.

like image 31
Noon Silk Avatar answered Oct 20 '22 01:10

Noon Silk