We are using an asynchronous HttpHandler in ASP.NET 3.5 under IIS 6, and in our code we're wanting to perform an external API call if we're not under too much load. We've defined "too much load" meaning that if we have more than X requests hitting this API at the same time, we'll just skip calling the API.
To accomplish this, we've wrapped our code in a Semaphore and Try/Catch/Finally. I feel like there's no way for this code to execute without releasing the semaphore, but with some additional logging, we're seeing that under heavy load the release statement is never being called.
The code is this:
static Semaphore requestLimiter = new Semaphore(500, 500);
...
String GetResultFromAPI() {
if (!requestLimiter.WaitOne(0)) return null;
try
{
// ... code to perform API call, with a timeout specified on the HttpWebRequest
return result;
} catch { /* ignore exceptions */ }
finally
{
requestLimiter.Release();
}
return null;
}
We've seen the exceptions for when the HttpWebRequest does time out, so we're puzzled as to how this code could result in the requestLimiter semaphore getting down to 0 and never recovering.
Has anyone encountered this? Is there any way an asynchronous HttpHandler can have a request interrupted without an exception?
Edit
Apparently ThreadAbortExceptions are a nasty beast that this code will definitely fail under. We aren't explicitly calling Thread.Abort, nor do I think HttpWebRequest would. However, now the revised question is: does ASP.NET ever call Thread.Abort for asynchronous http requests?