Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore ThreadAbortException when logging exceptions

What's the correct way of ignoring ThreadAbortException when logging exceptions?

Is it safe to just catch it in an empty catch block to make it disappear?

like image 362
Farinha Avatar asked Jun 26 '26 07:06

Farinha


2 Answers

If you need to stop a ThreadAbortException propogating further up the call stack, you can call Thread.ResetAbort. So try something like:

try
{
  // some code
}
catch (ThreadAbortException ex)
{
  // do some logging
  Thread.ResetAbort();
}

As for "correct" - that depends on your usage scenario. I'd generally be cautious about catching these unless you understand exactly why it has been raised. In escence it is a "stop now, quickly, and drop what you are doing" signal. Resetting it and going on to do further processing should be done with caution.

like image 102
Rob Levine Avatar answered Jun 28 '26 11:06

Rob Levine


Employ two catch blocks: one for ThreadAbortException and one for the rest, for example:

void MainLoop()
{   bool workdone;
    try
    {   while( IsWorking ) // cross-thread volatile variable
        {   workdone = Process();
            if( !workdone )
            {   Thread.Sleep( 500 );  }
        }
    }
    catch( ThreadAbortException )
    {   // Forced termination. Exit silently.
    }
    catch (Exception e)
    {   LogError( e );  }
}
like image 28
Ant_222 Avatar answered Jun 28 '26 11:06

Ant_222



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!