Response.Redirect(url) : Solution for ThreadAbortException
Posted by Vakul Kumar More on April 13, 2011
From the early days of using ASP.NET, we use Server.Transfer(URL) and Response.Redirect(URL). These simple calls used in ASP would never create problems but, in ASP.NET an exception is thrown when used.
The ThreadAbortException is thrown when a call is made to Response.Redirect(url). This happens because the system aborts processing of the current web page thread after it sends the redirect to the response stream. Internally, Response.Redirect(url) makes a call to Response.End() and that call Thread.Abort() which forces the stack to end the thread.
Many suggest using Try and Catch block. I feel it may not be a proper solution as processing exception can be costly. Best option would be to use an overload method of Response.Redirect() to redirect without calling Response.End().
Response.Redirect(string url, bool endResponse);
Response.Redirect(url, true) – The client will be sent the redirect for the new page and present page will immediately stop processing as a thread abort will occur. This is the default behavior of a redirect.
Response.Redirect(url, false) – In this overload method, the second parameter tells the system whether to make the internal call to Response.End() or not. Parameter should be false to make the client is sent to redirect url but call to Response.End is skipped. This is one way to avoid the exception, but the cost is that this thread doesn’t stop executing the Application events!
If you are doing a redirect in Page_Init (or any page events) and call Response.Redirect(url, false) the page will only redirect once the current page is done executing. This means that any server side processing you are performing on that page WILL get executed.
Though, there are cons of using both methods I personally prefer using Respose.Redirect(url,false).