简体   繁体   中英

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 is 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM