C# Developers' Journal (original) (raw)

5:38p

Non-blocking XmlTextReader I'm working on an application that needs to parse incoming XML messages from a NetworkStream. I've been using XmlTextReader, but have run into a couple problems.

I would like to make sure that a call to Read() on the XmlTextReader does not block in typical cases. That is, I would like to make sure that more input has arrived before making a call to Read(). Unfortunately, XmlTextReader seems to buffer data, but does not provide a means of determining whether any data has been buffered.

As an example, say I send

over the network stream. If I then call Read(), XmlTextReader will parse the

mojo

tag, as you would expect, but also pulls the

jojo

tag off of the NetworkStream and buffers it. A subsequent call to Read() would parse the

jojo

tag, but I have no way of knowing that I should make that next call, since the NetworkStream now reports that there is no data available, and XmlTextReader doesn't indicate that it has any data buffered. If I call Read() again "just in case", I could end up blocking if there is no more data data to read.

The obvious solution would seem to be to use an asynchronous delegate to avoid the blocking problem altogether, but, if I understand things properly, if I had 25 blocked calls to XmlTextReader.Read() (which isn't unlikely in this scenario), the thread pool would be exhausted, and connections that were ready to be read from would have to wait.

I'm about ready to give up and write my own simple XML parser, but thought I'd post here to see if maybe I'm missing some obvious solution to the problem. Any ideas?