问题描述
有时我在通过 URL 读取 XML 时遇到超时异常.我可以做些什么来防止这种情况发生,还是远程服务器有问题?下面是我的简单代码:
Sometimes I am getting a time out exception when reading an XML via a URL. Is there something I can do to prevent this, or is this a problem with the remote server? Below is my simple code:
XmlDocument doc = new XmlDocument();
doc.Load(XmlReader.Create(this.RssUrl));
我看到一篇帖子说 KeepAlive 可能会有所帮助,但我不知道如何将该设置传递到上面的代码中(或者这是否是正确的解决方案):http://www.velocityreviews.com/forums/t95843-system-webexception-the-operation-has-timed-out.html
I cam across a post that says KeepAlive may help, but I do not know how to pass that setting into the code above (or if that is even the correct solution): http://www.velocityreviews.com/forums/t95843-system-webexception-the-operation-has-timed-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.
I had this problem earlier and found this unanswered question. An option I have found is to prevent the request from timing out at all, which you can do creating your own WebRequest with a timeout of Timeout.Infinite and passing it into the 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,虽然默认情况下它实际上是 true,所以它应该没有任何区别.
You can also set the KeepAlive if you use a HttpWebRequest, although it is actually true by default, so it should not make any difference.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.RssUrl);
request.KeepAlive = true;
这篇关于使用 XmlReader.Create(uri) 防止或处理超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!