我的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,那么它不需要处理.