使用XmlReader.Create(uri)防止或处理超时

有时我通过URL读取XML时会遇到超时exception。 有什么我可以做的来防止这种情况,或者这是远程服务器的问题? 下面是我的简单代码:

XmlDocument doc = new XmlDocument(); doc.Load(XmlReader.Create(this.RssUrl)); 

我发现一篇文章说KeepAlive可能有所帮助,但我不知道如何将该设置传递到上面的代码中(或者如果这是正确的解决方案): http : //www.velocityreviews.com/forums/t95843-系统引发WebException最操作具有定时,out.html

这是例外,请帮忙!

 Exception Details: System.Net.WebException: The operation has timed out Stack Trace: [WebException: The operation has timed out] System.Net.HttpWebRequest.GetResponse() +5375213 System.Xml.XmlDownloadManager.GetNonFileStream(Uri uri, ICredentials credentials) +69 System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials) +3929371 System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn) +54 System.Xml.XmlReader.Create(String inputUri, XmlReaderSettings settings, XmlParserContext inputContext) +144 System.Xml.XmlReader.Create(String inputUri) +8 

我之前遇到过这个问题,发现这个问题没有答案。 我发现的一个选项是防止请求完全超时,你可以创建自己的WebRequest ,超时Timeout.Infinite并将其传递给XmlReader。

 WebRequest request = WebRequest.Create(this.RssUrl); request.Timeout = Timeout.Infinite; using (WebResponse response = request.GetResponse()) using (XmlReader reader = XmlReader.Create(response.GetResponseStream())) { // Blah blah... } 

如果你使用HttpWebRequest,你也可以设置KeepAlive,虽然默认情况下它实际上是真的,所以它不应该有任何区别。

 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.RssUrl); request.KeepAlive = true;