Two C# Guys

Monday, June 21, 2004

ASP.Net: Server.Transfer() and "Thread was being aborted."

I recently ran into something that was beginning to ruin my day. Check out the following snippet of ASP.Net code:

private void Page_Load(object sender, System.EvenArgs e)
{
   try
   {
      // (Do some stuff, then ... )
      Server.Transfer("AnotherPage.aspx");
   }
   catch (Exception ex)
   {
      throw new Exception(ex.Message, ex);
   }
}

Looks innocent, right? Wrong!

Here's what's wrong. When the Server.Transer() is executed, the catch clause catches the following exception: "Thread was being aborted." And if you have a custom error page it will catch that exception every time you do a Server.Transfer().

One suggestion, which worked for me, is to use Server.Execute() instead of Server.Transfer(). The main difference is that Server.Transfer() terminates execution of the current page (which is what causes the exception), and Server.Execute() executes the specified page and then returns control to the current page, much like a function call. There are other differences, but I'm not going to get into them here. Suffice to say, that Server.Execute() won't cause the "Thread was being aborted" exception to be thrown.

Cheers.

3 Comments:

  • Just an FYI, when you want to "re-throw" an exception, just use "throw;" like

    try{
    ...
    }
    catch(Exception)
    {
    throw;
    }

    That will maintain the call stack of the previous exception, rather than offering up a wrong line of a wrapped throw.

    Additionally, you can do this to hide the ThreadAbort:

    try{
    ...
    }
    catch(ThreadAbortException)
    {
    //swallow
    }
    catch(Exception)
    {
    throw; //all others
    }


    Scott Hanselman
    http://www.computerzen.com
    scott@hanselman.com

    By Anonymous Anonymous, at 9:40 PM  

  • I am using a code like this, but it still does not work fo me, the page fall into catch statement.

    string mailMessage;
    StringWriter mailText = new StringWriter();

    try
    {
    Server.Execute("~/mail/Sale.aspx?sid=" + SaleCheckOut.ID.ToString(), mailText);


    }
    catch (ThreadAbortException ex)
    {
    LogException(ex, "");
    }
    catch (Exception ex)
    {
    LogException(ex, "");
    }

    By Blogger Seyfullah Tıkıç, at 8:21 AM  

  • Ha, love the comment by the guy above on using "throw". Or should I say I love the way you've created a new exception with the same message ;o)

    By Anonymous EDW, at 10:24 PM  

Post a Comment

<< Home