Tuesday 18 September 2012

To Avoid ThreadAbortException in ASP.NET while Redirect

If you use the Response.End, Response.Redirect, or Server.Transfer method in your code then a ThreadAbortException occurs and the response is ended/aborted immediately.

For example, the line:
Response.Redirect("MyHome.aspx") //your response will be aborted

The ThreadAbortException is thrown when you make a call to Response.Redirect(url) because the system aborts processing of the current web page thread after it sends the redirect to the response stream. Response.Redirect(url) actually makes a call to Response.End() internally, and it's Response.End() that calls Thread.Abort() which bubbles up the stack to end the thread.Under rare circumstances the call to Response.End() actually doesn't call Thread.Abort(), but instead calls HttpApplication.CompleteRequest().

 Response.Redirect(String, Boolean) - Redirects a client to a new URL. Specifies the new URL and whether execution of the current page should terminate.
 Response.Redirect(string url, bool endResponse)

using Response.Redirect(url, false),

You don't need to put the redirect in a try-catch block. Just replace all calls to Response.Redirect(url) with the following lines:

Response.Redirect(url, false);

When endResponse is false the client is sent the redirect url, but the internal call to Response.End is skipped. This completely avoids the code that would throw the exception, but the cost is that this thread doesn't stop executing the Application events.

The way to get over this problem is to specify Response.Redirect(URL,false) , this will tell .NET framework not to stop the execution of the current thread and hence the error will be resolved.

“ThreadAbortException” is a special kind of an exception even if you catch it in a catch block even then it will be raised again at the end of the catch block. When this exception is raised, the runtime executes all the finally blocks before killing the thread.


If endResponse=true (or if the other overload is used), the exception is thrown and the current request will immediately be terminated. A true will just kill the thread so nothing further will execute, which in turn throws a ThreadAbortException.


No comments:

Post a Comment