【问题标题】:Prevent or handle time out with XmlReader.Create(uri)使用 XmlReader.Create(uri) 防止或处理超时
【发布时间】:2011-04-02 15:40:56
【问题描述】:

有时我在通过 URL 读取 XML 时遇到超时异常。我可以做些什么来防止这种情况发生,还是远程服务器有问题?下面是我的简单代码:

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

这是个例外,请帮忙!

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

【问题讨论】:

    标签: c# .net asp.net .net-3.5 xmlhttprequest


    【解决方案1】:

    我之前遇到过这个问题,发现了这个没有答案的问题。我发现的一个选项是完全防止请求超时,您可以创建自己的 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,虽然默认情况下它实际上是 true,所以它应该没有任何区别。

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

    【讨论】:

    • 您好 Fara,我已经完全按照您发布的方式使用了,但我仍然收到此错误。
    猜你喜欢
    • 2010-09-17
    • 2011-05-30
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-06
    相关资源
    最近更新 更多