Caveman's Blog

My commitment to learning.

Archive for the ‘ThreadAbort’ Category

The Response.Redirect Menace

with one comment


You know how we all take things for granted and never bother to think of the caveats…. yep you know what I am talking about…. exactly… I ran into one such situation with Response.Redirect.

I have learnt that the Response.Redirect internally has to make a call to Response.End to force stop the execution of the current thread there by throwing a ThreadAbort exception [2].

The way this works is:

A call to HttpResponse.Redirect(string url) actually calls an overload HttpResponse.Redirect(string url, bool endResponse) with endResponse set to true. If endResponse is set to true, HttpResponse.Redirect will make a call to HttpResponse.End(). [1]

Microsoft recommends that we use the overloaded Response.Redirect(String url, bool endResponse) method that passes false so that a call to Thread.Abort() can be avoided by suppressing the call to Response.End. Is there a catch? Yes, the page will execute the code that follows Response.Redirect.

One solution I can think of to minimize the effort in execution of the code that follows the Response.Redirect is, actually code around the Response.Redirect

if(HaveToredirect == true)
{
  Response.Redirect(url, false); //as described in [1]
  HttpContext.ApplicationInstance.CompleteRequest();
  return;
}

Check for the IsRequestBeingRedirected property of the Response object and return if it is true, in all the page events as the first step. This way we can mimimize the execution time of the page.

if (Response.IsRequestBeingRedirected == true)
return;

This approach might be feasible in all scenarios though.

Also note that Server.Transfer calls Response.End interally.

References:

1. Response.Redirect(url) ThreadAbortException Solution
2. Microsoft Support Article.

Written by cavemansblog

February 13, 2008 at 3:09 pm