How to specify timeout for XmlReader?
Asked Answered
F

4

7

I am reading rss with xml reader.

And when url is bad it takes 60 seconds to fail for it. How i can specify timeout?

using (XmlReader reader = XmlReader.Create(url, settings))
Forworn answered 26/1, 2011 at 19:19 Comment(0)
K
17

I don't know if it's possible to change the XmlReader timeout, but maybe you can do something different:

Use WebRequest to get the xml (this does have a Timeout property) and feed XmlReader this xml after you have received it:

WebRequest request = WebRequest.Create(url);
request.Timeout = 5000;

using (WebResponse response = request.GetResponse())
using (XmlReader reader = XmlReader.Create(response.GetResponseStream()))
{
    // Blah blah...
}
Kmeson answered 26/1, 2011 at 19:21 Comment(2)
You may also want to look into threading to spin this process off onto a background thread so it doesn't block your UI, if that's a concern in your case.Kmeson
i was expecting that this is only option. Thank you for detailed codeForworn
S
1

You can create your own WebRequest and create an XmlReader from the response stream. See the response to this question for details:

Prevent or handle time out with XmlReader.Create(uri)

Sonora answered 26/1, 2011 at 19:26 Comment(0)
M
0

Pass your own stream to the XmlReader.Create call. Set whatever timeout you like.

Mirabel answered 26/1, 2011 at 19:22 Comment(0)
F
0

Another option is to do this

var settings = new XmlReaderSettings();
settings.XmlResolver = resolver;

// Create the reader.
XmlReader reader = XmlReader.Create("http://serverName/data/books.xml", settings);

Where the resolver instance is a custom class that changes the url fetching behavior as described in the documentation at the link below.

https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmlurlresolver?view=net-6.0#extending-the-xmlurlresolver-class

Flan answered 26/1, 2022 at 8:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.