10

When writing the below my code locks up on GetResponse. Why?

        try
        {
            WebRequest myWebRequest = WebRequest.Create(strURL);
            WebResponse myWebResponse = myWebRequest.GetResponse();
            //more code here
  • No problem when trying this on http://localhost whats the URI? – Ralf de Kleine Sep 06 '09 at 20:28
  • There's not enough information to diagnose this. Does it lock up for you regardless of which URL you use, is it only for one URL, does it happen consistently, what happens when you try to access the URL from your browser? – Pete OHanlon Sep 06 '09 at 20:31

1 Answers1

46

This usually happens if you've made several requests to the same host, and not disposed of the WebResponse.

The default connection management settings only allow 2 (or maybe 4, I can't remember) open connections to the same host at a time. If you really need to change this, use the <connectionManagement> app.config element - but usually you'll be fine just disposing of WebResponse:

try
{
    WebRequest myWebRequest = WebRequest.Create(strURL);
    using (WebResponse myWebResponse = myWebRequest.GetResponse())
    {
        //more code here
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    I <3 Jon Skeet that fixed the problem completely. Again i would have never to check for dispose. Thanks. –  Sep 06 '09 at 21:28
  • 2
    That didnt help for me. I tried the "using" approach, as well as doing a Close on the response inside the using... but still get the same problem. – Ted Dec 04 '11 at 19:21
  • My question on SO: http://stackoverflow.com/questions/8377185/c2dm-frequent-timeouts-or-errors-when-sending-webservice-does-not-respond – Ted Dec 04 '11 at 19:27
  • @John Skeet, I have a scenario where I want to return large data as continuous stream. If I placed my return `myWebResponse.GetResponseStream()`, will it not `Close()` the stream before the entire stream is returned?... if I do not use the `using` statement,won't that that also mean that `myWebResponse` will not be properly disposed?... I know I can close the `Stream` at my calling function, but not sure what happens to the `WebResponse` object – tinonetic Mar 19 '15 at 03:17
  • Solved it! wrote a void method that has two `Stream` parameters, one incoming and the other being written to, as per convention for streams. Disposes nicely! – tinonetic Mar 19 '15 at 03:22