Why Response.Redirect() Causes Thread Abort Exception and How To Solve
Thread abort exceptions can often be caused by calling Response.Redirect(myurl) within your Web Application and it may not be obvious to the developer what could be wrong with this or indeed why it would lead to an exception. Typically, you can expect to get a thread abort exception that looks like the below:
Exception: System.Threading.ThreadAbortException: Thread was being aborted.
What causes this? When calling Response.Redirect(...) with only a Url parameter, the endResponse flag by default is set to true. When set true, this flag ends the page execution (aborting the thread that would otherwise have continued building up the response had it not hit your redirect call) and shifts execution to the Application_EndRequest event. This aborting of the thread (and abnormal termination of building upt he response) is what causes the exception.
In an ideal world, the best practice would be to avoid building up a response at all if you suspect the need to redirect (perhaps testing the condition that would lead to the redirect before trying to render a page at all). But in practice, the need to redirect can crop up anywhere and if you find yourself plagued by these exceptions, you can easily solve it by calling:
Response.Redirect(myurl, false) Context.ApplicationInstance.CompleteRequest();
The extra parameter on Redirect(...) sets the endResponse flag to false, allowing the first thread to complete its execution all the way to the end (as a result, will not give the 'thread abort exception'). The second method CompleteRequest() then tells .NET to skip all future stages in the ASP.NET pipeline and jump directly to the EndRequest step (since you are redirecting, there is nothing more that needs to be done with the current request).
This not only will remove all Thread Abort Exceptions and annoying "ThreadAbortException: Thread was being aborted." you may see in logs, but will also invoke (in a sympathetic way!) all the .NET goodies to clean up after themselves in a way that's fairly efficient.
Need an Umbraco Master?
Here at Simon Antony, we have an in house certified Umbraco Grand Master available for hire. Got a problem with your site, need architecture advice, give us a call to speak to Simon directly and see how we can helpContact Simon Today!