Home > Blogs > The hanging web request

The hanging web request

By  Oct 2, 2007


I've had this nagging bug in my program for a while.  Periodically a Web request would just hang for no apparent reason.  I just put it up with it while I had more important fish to fry, but this problem finally worked its way to the top of the priority list.

The really odd part about this bug was the lack of a cause.  Sometimes I'd see that the request failed somehow (a 404 error or some error reading the response), but other times it would ... just hang.  I could run the same URL through the same code again and everything would work fine.  The problem did seem to occur on some domains more than on others, but I couldn't reliably duplicate it.  It happened infrequently enough that I couldn't just single-step through the code to find the cause.

So I resorted to brute force.  I added some tracing code and started the program, waiting for the it to hang on some URL.  Sure enough, after a few minutes the bug appeared and I found out where it was hanging.  It was hanging somewhere in this code:

if (response != null)
    response = null;

if (streamResponse != null)
    streamResponse = null;

A little more investigation showed that it was hanging in the call to response.Close.  I still don't know why it happens, but I found a solution.  If I abort the associated web request before trying to close the response, the hang problem goes away.  I just added a call to request.Abort before the code shown above and everything seems to work.

It feels like a hack, and I'd sure like to understand what's going on that makes response.Close hang like that, but I don't have infinite time to track these things down.  If you have information as to what causes this, I'd sure like to hear it.

Become an InformIT Member

Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.