.net – What might cause ThreadAbortException when using HttpWebRequest.GetResponse()

.net

I'm living in nightmares because of this situation, I have a HttpWebRequest.GetResponse that keeps on giving me a ThreadAbortException, that causes the whole app to go down.

How can I avoid that, or at least handle it, would using Thread.ResetAbort() be useful in such a case?

To explain more here is a rough code sample:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://someurl.com/");
HttpWebResponse resp = req.GetResponse();

now the last line above throws the ThreadAbortException, it might be because the request timed out which is fine, but I don't want to get a ThreadAbortException inside my ASP.NET 2.0 app because it kills it. The ThreadAborException can't be caught with try/catch, the only way to handle it is using Thread.ResetAbort() which has its own bad effects too, it will keep the thread alive and god only knows for how long.

Best Solution

From what you say it seems you are making an outgoing WebRequest to an external resource from within the processing of an incoming request to an ASP.NET application. There are (at least) two timeouts that are relevant here:

  • WebRequest.Timeout (default 100000ms = 100s) specifies the timeout for execution of the outgoing WebRequest. If this timeout expires, you should get a WebException - so this isn't your problem.

  • The HttpRuntime that is processing your incoming request has an execution timeout: the default value according to MSDN is 110s for .NET 2.0 or later, 90s for .NET 1.x. When this timeout expires, you'll get a ThreadAbortException. It looks like this is what is happening.

In .NET 1.x, you'd expect this, because the default HttpRuntime executionTimeout is less than WebRequest.Timeout. In .NET 2.0, you'd expect this with the default timeouts if you have already spent >10s before making the outgoing WebRequest (e.g. if you have more than one outgoing WebRequest from within the same incoming request).

I would suggest you either:

  • Reduce the WebRequest.Timeout for outgoing requests, and handle WebException, or

  • If the outgoing requests can really take that long, then increase the httpRuntime execution timeout as described in MSDN.