Tuesday, 20 March 2012

"Thread was being aborted." Error occurred due to Response.End, Response.Redirect, or Server.Transfer method methods

Click Here to Download Sample ThreadWasBeingAbortedExample.zip
Note : In this sample application there is two pages First page "ErrorSample.aspx" This page dmostrate how this error occured you can check this by putting debug point in Catch section, you notice that when Response.Redirect method called after that error thow and page is being redirected. Second page is "ErrorResolvedExample.aspx" in this page we demostrate how to resolve this issue.

When you are using Response.End, Response.Redirect, or Server.Transfer method methods in Try Catch Block it will throw "ThreadAbortException" Exception.
Error Message like "Thread was being aborted."

The Reason for this error due to.
The Response.End method ends the page execution and shifts the execution to the Application_EndRequest event in the application's event pipeline.
The line of code that follows Response.End is not executed.

This problem occurs in the Response.Redirect and Server.Transfer methods because both methods call Response.End internally.

Solution for this Problem is as follows.

For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest method
instead of Response.End to bypass the code execution to the Application_EndRequest event.

Example :
HttpContext.Current.ApplicationInstance.CompleteRequest();

For Response.Redirect, use an overload, Response.Redirect(String url, bool endResponse) Method.
Pass false for the end Response parameter to suppress the internal call to Response.End.

Example :
 Response.Redirect ("otherpage.aspx", false);

For Server.Transfer, use the Server.Execute method instead.

Example :
Server.Execute("otherpage.aspx");

4 comments:

  1. Hello sir, I have make all the changes but the same error is coming in my application.
    It throw an exception "Thread was being aborted"

    ReplyDelete
    Replies
    1. Hi,
      Can you paste your code here ? so i can check

      Delete
  2. thanks. this post has cleared the problem and i can able to solve my problem...

    ReplyDelete
  3. Good stuff very useful

    ReplyDelete