Monday, July 7, 2014

Catch ThreadAbortException in ASP.Net

In ASP.Net, whenever a redirect or response end statement is executed, ThreadAbortException is thrown and it is logged in event viewer.

System.Threading.ThreadAbortException Message: Thread was being aborted. 
Source: mscorlib at System.Threading.Thread.AbortInternal() 
at System.Threading.Thread.Abort(Object stateInfo) 
at System.Web.HttpResponse.End() 

To avoid thread ThreadAbortException related messages in logging, call to Response.Redirect and Response.End methods should be wrapped in try-catch block. Simply catching this exception will not work as the exception is thrown again even after getting caught. So, in the catch block a call should be made to Thread.ResetAbort() method.

E.g.:
try
{
    HttpContext.Current.Response.End();
}
catch(ThreadAbortException ex)
{
    //Exception is again thrown after catch block.
    //To suppress it call ResetAbort method of System.Threading.Thread
    System.Threading.Thread.ResetAbort();
}