Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpWebResponse

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?

like image 265
user1855271 Avatar asked Nov 28 '12 15:11

user1855271


1 Answers

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.

like image 122
Mike Simmons Avatar answered Sep 21 '22 00:09

Mike Simmons