C# HttpWebResponse Timeout doesn't work

江枫思渺然 提交于 2019-12-14 02:24:40

问题


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.


回答1:


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"?




回答2:


Try this property: ReadWriteTimeout



来源:https://stackoverflow.com/questions/6295017/c-sharp-httpwebresponse-timeout-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!