6

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).

Ash
  • 24,276
  • 34
  • 107
  • 152

2 Answers2

19

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
}
Marco Forberg
  • 2,634
  • 5
  • 22
  • 33
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    Well, it isnt actually. Its the same problem. And it was "solved" by telling the request to use HTTP 1.0, not 1.1. See here: http://stackoverflow.com/a/8384691/178143 – Ted Dec 05 '11 at 16:17
  • @Ted: It may have had the same symptoms, but if disposing the response solved it for the OP but didn't solve it for you, that suggests it wasn't the same underlying problem. – Jon Skeet Dec 05 '11 at 16:23
  • Perhaps =) In any case its a pretty strange error to have... Thx for replying =) – Ted Dec 05 '11 at 16:43
1

Yep, your exactly right. The response wasn't being disposed properly. We'd been leaving this upto the garbage collector, which, you guessed it, wasnt being collected in time. Unfortunately, I closed my browser and forgot to read any answers (lol how stupid do you think I feel) and the problem is solved.

I've learned 2 things tonight. 1, dispose of your WebRequests properly; and 2, PAY MORE ATTENTION TO STACK-OVERFLOW ANSWERS!

Ash
  • 24,276
  • 34
  • 107
  • 152
  • Main thing is to *never* rely on the garbage collector to finalize things which implement IDisposable but you don't *know* are safe (e.g. MemoryStream). – Jon Skeet Jan 20 '09 at 11:49