【问题标题】:WebRequest Exception in .NET.NET 中的 WebRequest 异常
【发布时间】:2011-01-21 19:25:12
【问题描述】:

我使用此代码 sn-p 来验证 URL 中指定的文件是否存在,并每隔几秒钟为每个用户尝试一次。有时(主要是当有大量用户使用该站点时)代码不起作用。

    [WebMethod()]
    public static string GetStatus(string URL)
    {
        bool completed = false;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            try
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    completed = true;
                }
            }
            catch (Exception)
            {
                //Just don't do anything. Retry after few seconds
            }
        }

        return completed.ToString();
    }

当我查看 Windows 事件日志时,有几个错误:

Unable to read data from the transport connection. An existing connection was forcibly closed

The Operation has timed out

The remote host closed the connection. The error code is 0x800703E3

当我重新启动 IIS 时,一切正常,直到下次发生这种情况。

【问题讨论】:

    标签: c# asp.net iis exception scalability


    【解决方案1】:

    您将 try/catch 放在 using 语句中,而 request.GetResponse 方法可能会抛出:

    bool completed = false;
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
    try
    {
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            if (response.StatusCode == HttpStatusCode.OK)
            {
                completed = true;
            }
        }
    }
    catch (Exception)
    {
        //Just don't do anything. Retry after few seconds
    }
    return completed.ToString();
    

    【讨论】:

    • 你能解释一下你为什么会抛出这个异常吗?我确实读过需要设置为 false 的 KeepAlive 属性,但不确定在这种情况下是否必须这样做。
    • HTTP请求超时的可能场景太多了。
    • 理论上,当 HTTP 请求超时时,我认为它会简单地关闭连接。我不知道为什么其他用户会在一个连接超时后立即受到影响。
    • 因为 ASP.NET 使用线程池来处理请求,并且当该池中的所有线程都已耗尽以等待来自远程服务器的响应时,Web 服务将不再能够接受新的请求。对于慢速请求,建议使用依赖 IOCP 的异步 API。 (例如:BeginGetResponse、EndGetResponse)
    • 现在说得通了。我是否需要在 catch 块中添加逻辑以强制关闭/释放连接?或者只是将其包装在 try catch 中就足够了?
    猜你喜欢
    • 1970-01-01
    • 2012-04-23
    • 2014-08-22
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 1970-01-01
    • 2012-08-13
    相关资源
    最近更新 更多