Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpWebRequests Failing on Subsequent Calls

I know this is a vague question, especially since I am not providing any code, but I am developing a .Net 2.0 application, and we have a WebRequest which posts data to an internally built API.

The strange thing happens on our 3rd (and always the 3rd) subsequent request which fails at the GetRequestStream() method of the request. The first and second time its called, all is fine. On the 3rd time, it hangs for a bit and eventually times out.

The API is being called by other applications in house, so we know its not a server-side, or networking issue. We've tried on several machines - all of which have the same problem. Has anyone ever had this problem before, or does anyone have any sugestions about how to debug (since the response object doesn't yeild anything, or at least nothing useful).

like image 437
Ash Avatar asked Jan 20 '09 10:01

Ash


1 Answers

This usually happens if you're not disposing the WebResponse. There's a limit applied to the number of connections from a client to the same machine, and by default it's two. The connections can be reused (or closed) if you close the WebResponse. The using statement is your friend here:

WebRequest request = [...];
// Do stuff with the request stream here (and dispose it)
using (WebResponse response = request.GetResponse())
{
    // Stuff with the response
}
like image 184
Jon Skeet Avatar answered Oct 04 '22 17:10

Jon Skeet