ASP.Net: Avoid ThreadAbortException on Response.Redirect


Scenario:

You are writing a WebForms application and you want to avoid the final ThreadAbortException that is thrown whenever you do a Response.Redirect.

Solution:

Exception are generally expensive when they are generated which is why it's almost always better to avoid having them thrown all together with logic checks. In this case, ending the response early causes the ThreadAbort since the rest of the page life cycle is cut short. We can avoid this with just an additional line of code:

VB.Net

Response.Redirect("ThankYou.aspx", False)
HttpContext.Current.ApplicationInstance.CompleteRequest()

C#

Response.Redirect("ThankYou.aspx", false);
HttpContext.Current.ApplicationInstance.CompleteRequest();

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.