简体   繁体   中英

StreamReader issues

i was trying to break my newly made servlet earlier and ended up breaking my own application, i kind of wish i hadn't bothered now!

response = (HttpWebResponse)request.GetResponse();
reader = new StreamReader(response.GetResponseStream());
String streamedXML = reader.ReadToEnd(); // 
XmlDocument doc = new XmlDocument();
doc.LoadXml(streamedXML);

If i open up 10 windows or so, then rapidly request data from my servlets (this is the same 10 windows, returning the same data) then i get an xml exception being thrown;

Unexpected end of file has occurred. The following elements are not closed:

The thing is, if i run this one at a time, or with a large gap between requests then if completes fine. Is this because my streamreader is being overwehlmed by requests and starting new ones before others have finished? If so, is there a better way of writing this data?

Thanks.

You could try to fix this code or leave it to the experts and use a WebClient:

using (var client = new WebClient())
{
     string streamedXML = client.DownloadString(sourceUrl);
     ...

}

And personally I would use XDocument instead of XmlDocument, but that depends.

The StreamReader isn't overwhelmed. (It could only block or raise IO Exceptions / Out Of Memory exceptions)

However, it would seem that the server it is talking to is overwhelmed.

Find out with fiddler or in the server logs

You could start by disposing of everything correctly and seeing if that helps:

using(response = (HttpWebResponse)request.GetResponse())
using(reader = new StreamReader(response.GetResponseStream()))
{
    String streamedXML = reader.ReadToEnd(); // 
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(streamedXML);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM