Avoid ThreadAbortException in ASP.NET with Response.Redirect
![]()
Server.Transfer() method on ASP.NET has its own advantages and so once we get hooked up with the Server.Transfer() method we tend to avoid Response.Redirect() method as much as we can. But there are circumstances when you want to avoid Server.Transfer() to let the client know about the exact URL location and so we might end up using Response.Redirect().
When you try to redirect from a page with Response.Redirect(”url”) some times you might end up with a ThreadAbortException. The cause of the exception is that at times ASP.NET, instead of calling the Thread.Abort() method it calls HttpApplication.CompleteRequest() and that messes up the ASP.NET call stack and throws the ThreadAbort exception.
One way to resolve this is to cover it up with a Try-Catch block.
try{Response.Redirect(url);}catch (ThreadAbortException ex){}
Even though it resolves the problem it truly is expensive as exceptions are always expensive. So what would be the right thing to do?
Here is the syntax of Response.Redirect()
public Redirect(string url, bool endResponse);
So to avoid the ThreadAbortException pass in “FALSE” as the second argument to the endResponse parameter,
Response.Redirect(url, false);
This should take care of the ThreadAbortException. When this parameter is set to ”false” the client is sent the redirect url, but the internal call to Response.End() is skipped. This skips the code path that would throw the exception, but the cost is that this thread doesn’t stop executing the Application events completely. Thankfully we can resolve that problem by duplicating the step that Response.End() takes under those rare circumstances, namely calling the HttpApplication.CompleteRequest() method explicitly.
HttpApplication.CompleteRequest() sets a variable that causes the thread to skip past most of the events in the HttpApplication event pipeline and go straight to the final event, named HttpApplication.EventEndRequest. This gracefully terminates the execution of the thread with a minimum of server resources.



December 18th, 2009 at 2:48 am
Hi.
My computer worked slowly, too much errors. Help me, please to fix errors on my PC.
I used Windows7.
With best regards,
nedHaiseanemi