Why am I getting "Thread was being aborted" in ASP.NET?

I am not sure why this happens and I never explicitly abort threads, so it's a bit of a surprise. But I log Exceptions and I am seeing:

System.Threading.ThreadAbortException - Thread was being aborted.

It appears to happen in a call to System.Threading.WaitHandle.WaitOne. I am not sure how far this Exception goes. I don't think my threads ever terminate, because I catch log and swallow the error.

Why am I getting these errors? Perhaps it's when I am forcefully terminating my server or asking it to reboot? If it isn't then what might be causing them?

235714 次浏览

Nope, ThreadAbortException is thrown by a simple Response.Redirect

ASP.NET spawns and kills worker processes all the time as needed. Your thread may just be getting shut down by ASP.NET.

Old Answer:

Known issue: PRB: ThreadAbortException Occurs If You Use Response.End, Response.Redirect, or Server.Transfer

Response.Redirect ("bla.aspx", false);

or

try
{
Response.Redirect("bla.aspx");
}
catch (ThreadAbortException ex)
{
}

If you spawn threads in Application_Start, they will still be executing in the application pool's AppDomain.

If an application is idle for some time (meaning that no requests are coming in), or certain other conditions are met, ASP.NET will recycle the entire AppDomain.

When that happens, any threads that you started from that AppDomain, including those from Application_Start, will be aborted.

Lots more on application pools and recycling in this question: What exactly is Appdomain recycling

If you are trying to run a long-running process within IIS/ASP.NET, the short answer is usually "Don't". That's what Windows Services are for.

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

The solution for this problem is as follows.

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

Visit this link for download an example.

For a web service hosted in ASP.NET, the configuration property is executionTimeout:

<configuration> <system.web>


<httpRuntime executionTimeout="360" />


</system.web>


</configuration>

Set this and the thread abort exception will go away :)

This error can be caused by trying to end a response more than once. As other answers already mentioned, there are various methods that will end a response (like Response.End, or Response.Redirect). If you call more than one in a row, you'll get this error.

I came across this error when I tried to use Response.End after using Response.TransmitFile which seems to end the response too.

I got this error when I did a Response.Redirect after a successful login of the user.

I fixed it by doing a FormsAuthentication.RedirectFromLoginPage instead.