C#HttpWebResponse超时不起作用 [英] C# HttpWebResponse Timeout doesn't work

查看:908
本文介绍了C#HttpWebResponse超时不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有检查网站是否可用的功能.

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.

问题是某些网站不可用. 我想等待x毫秒(在reqFP.Timeout中设置),然后函数应该返回false. 但是每次我都必须等待约20秒(即使我将超时"设置为10秒).

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:很抱歉出现语言错误.

PS: Sorry for language mistakes.

推荐答案

来自 MSDN文章:

域名系统(DNS)查询可能 最多需要15秒才能返回,或者 暂停.如果您的请求包含 需要解析的主机名和 您将超时"的值设置为小于 15秒,可能需要15秒或 在抛出WebException之前还有更多 表示您的请求超时.

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.

是否有可能?尝试使用合理的代码,但使用IP地址而不是主机名. 另外,在等待20秒后得到false,是否确定是因为超时而不是因为服务器返回的不是"200"?

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

这篇关于C#HttpWebResponse超时不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆