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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With