加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 如何在捕获httpwebrequest超时后关闭底层连接

发布时间:2020-12-16 04:04:38 所属栏目:asp.Net 来源:网络整理
导读:我的asp.net应用程序将httpwebrequest发送到远程REST服务器并等待响应,我发现有很多相同的错误消息,如下所示: System.Net.WebException: The operation has timed-out. at System.Net.HttpWebRequest.GetResponse() 在我捕获此异常并直接关闭底层http连接后
我的asp.net应用程序将httpwebrequest发送到远程REST服务器并等待响应,我发现有很多相同的错误消息,如下所示:

System.Net.WebException: The operation has timed-out. at
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();
}

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读