C# HttpWebResponse Timeout doesn't work
I have the function to check if website is available.
public bool ConnectionAvailable(string strServer)
{
try
{
HttpWebRequest reqFP = (HttpWebRequest)HttpWebRequest.Create(strServer);
reqFP.Timeout = 10000;
HttpWebResponse rspFP = (HttpWebResponse)reqFP.GetResponse();
if (HttpStatusCode.OK == rspFP.StatusCode)
{
// HTTP = 200 - Internet connection available, server online
rspFP.Close();
return true;
}
else
{
// Other status - Server or connection not available
rspFP.Close();
return false;
}
}
catch (WebException)
{
// Exception - connection not available
return false;
}
}
It's not mine code. I found it in the Net.
The problem is when some website isn't available. I want to wait x miliseconds (set in reqFP.Timeout), then function should return false. But everytime I have to wait ~20 seconds (even if i set 10 seconds in "timeout").
Do you have any idea what i开发者_C百科s wrong?
PS: Sorry for language mistakes.
From MSDN article:
A Domain Name System (DNS) query may take up to 15 seconds to return or time out. If your request contains a host name that requires resolution and you set Timeout to a value less than 15 seconds, it may take 15 seconds or more before a WebException is thrown to indicate a timeout on your request.
If it's possible that's the case? Try the sane code but using IP address instead of hostname.
Also, when you get false
after waiting 20 seconds, are you sure it's because of timeout and not because the server returned something other than "200"?
Try this property: ReadWriteTimeout
精彩评论