如何在捕获httpwebrequest超时后关闭底层连接

时间:2009-09-03 21:12:13

标签: asp.net httpwebrequest

我的asp.net应用程序将httpwebrequest发送到远程REST服务器并等待响应,我发现有很多相同的错误消息:

  

System.Net.WebException:操作已超时。在   System.Net.HttpWebRequest.GetResponse()

在我捕获此异常并直接关闭底层http连接后,这可能吗?或者我真的不必这样做,因为我已经将keepalive设置为false?

感谢。

实际上另一个问题是,如果超时异常总是发生在System.Net.HttpWebRequest.GetResponse(),那么这意味着应用程序正在等待来自远程服务器的响应,并且在超时之前无法获得响应。可能的原因是什么,网络连接不稳定?远程服务器无响应?任何其他可能的原因?

以下是代码:

System.Net.HttpWebResponse httpWebResponse = null;
System.IO.Stream stream  = null;
XmlTextReader xmlTextReader  = null;
try
{
    System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(request);
    httpWebRequest.ReadWriteTimeout = 10000;
    httpWebRequest.Timeout = 10000;
    httpWebRequest.KeepAlive = false;
    httpWebRequest.Method = "GET";
    httpWebResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse();
    stream = httpWebResponse.GetResponseStream();
    xmlTextReader = new  XmlTextReader(stream);
    xmlTextReader.Read();
    xmlDocument.Load(xmlTextReader);
    //Document processing code.
    //...
}
catch
{
    //Catch blcok with error handle
}
finally
{
    if (xmlTextReader != null)
        xmlTextReader.Close();
    if (httpWebResponse != null)
        httpWebResponse.Close();
    if (stream != null)
        stream.Close();
}

4 个答案:

答案 0 :(得分:2)

简单的经验法则是,如果它没有实现IDisposal,那么它就不需要处理。

答案 1 :(得分:1)

您还可以增加machine.config中的出站连接数:

<system.net>
  <connectionManagement>
     <add address="*" maxconnection="2" />
  </connectionManagement>
</system.net>

将maxconnection attr更改为更高的值,请参阅: http://www.williablog.net/williablog/post/2008/12/02/Increase-ASPNET-Scalability-Instantly.aspx

答案 2 :(得分:0)

确保处置和关闭。

或者使用使用块代替 try-finally

using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse()) {
    using (var stream = httpWebResponse.GetResponseStream()) {
        using (var xmlTextReader = new XmlTextReader(stream)) {
            xmlDocument.Load(xmlTextReader);
        }
    }
}

答案 3 :(得分:0)

您可以做的另一件事是在导致错误的HTTPWebRequest上调用Abort()方法,如下所示:

catch (WebException we)
{
    using (HttpWebResponse errorResp = we.Response as HttpWebResponse)
    {
    ...
    }
    request.Abort();
}