8

I want to download images from the server. When the image doesn't exist, I want to show my default image.

Here's my code:

string url = "http://www......d_common_conference" + "/" + c.id_common_conference + "-MDC.jpg";

try {
    HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
    request.Method = "HEAD";                        
    HttpWebResponse response = request.GetResponse() as HttpWebResponse;
    string status = Response.StatusCode.ToString();                                               

    img.ImageUrl = url;
}
catch (Exception excep) {
    img.ImageUrl = "images/silhouete.jpg";
    string msg = excep.Message;
} 

It works nice, but until the 24th loop, no response, no exception thrown, and my program becomes jammed.

How can I fix this?

Pang
  • 9,564
  • 146
  • 81
  • 122
user1855271
  • 81
  • 1
  • 2
  • you could perhaps try setting up a breakpoint and step into your code for further investigation.. what is the problem exactly? and as a quicknote, please make your question title more informative.. – Can Poyrazoğlu Nov 28 '12 at 16:12

1 Answers1

4

You aren't disposing of the HttpWebResponse, try this instead:

HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "HEAD";
string status;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
    status = response.StatusCode.ToString();
}

I suspect you've hit the limit on TCP connections your machine will make (can't remember the number, but it's per CPU if memory serves)

p.s. there was a typo in your example, you weren't using the response variable from your WebRequest, but the Response object for the current request.

Mike Simmons
  • 1,298
  • 1
  • 9
  • 22