blah blah blah is here! blah blah » Close

up1down
link

Hi all,

I made this method to automatically check if a website is up or not. It runs every minute from a Console app and for the first few minutes it seems to work. After that I start getting "The operation has timed out" errors. Any ideas?

private static void HTTPCheck(string url)
{
try
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
switch (((HttpWebResponse)req.GetResponse()).StatusCode)
{
case HttpStatusCode.OK:
//ok
break;
default:
//failed
break;
}
}
catch (Exception x)
{
WriteToLog(null, null, null, x.Message);
Console.WriteLine("{0} - {1}", DateTime.Now, x.Message);
//failed
}
}

last answered one year ago

2 answers

link

I can't see it being a blocking problem.

Looking again at the code, I think what it might be is that you're not closing the response and hence the connection and after a while you're running out of connection handles!

See if it's any better if you rearrange the code as follows:

private static void HTTPCheck(string url)
{
HttpWebResponse resp = null;

try
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
resp = (HttpWebResponse)req.GetResponse();
switch (resp.StatusCode)
{
case HttpStatusCode.OK:
//ok
break;
default:
//failed
break;
}
}
catch (Exception x)
{
WriteToLog(null, null, null, x.Message);
Console.WriteLine("{0} - {1}", DateTime.Now, x.Message);
//failed
}
finally
{
if(resp != null) resp.Close();
}
}

foamy
2499

Looks like that did the trick :D

up0down
link

The default timeout interval for HttpWebRequest is 100 seconds so, if it's a slow or busy site and you're checking every minute, it's possible that the previous request hasn't yet been responded to when a new one goes in.

I'd try checking every two minutes instead or leave it at one minute but reduce the timeout period to, say, 50 seconds before you call GetResponse():

req.Timeout = 50000;

foamy
2499

Well the site I tested my function with was http://www.google.com :-\ and that really should be able to handle it. Is my checking the site somehow getting blocked perhaps?

Feedback