Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrent XmlReader and XmlWriter

I have a system that creates some XmlReader and XmlWriter instances, and passes them to clients, so that the clients can write and read XML.

Sometimes, multiple threads access the system:

  1. Thread 1 gets an XmlWriter instance and starts writing
  2. Thread 2 gets an XmlReader instance that represents the same XML document, and starts reading.

Obviously, sometimes the reader starts reading before the writer has completed writing, which causes an exception to be thrown in the reader:

System.Xml.XmlException : Root element is missing.

That's not particularly surprising, but is there any way to make this system thread-safe?

  • Is it possible to make the reader read while the writer writes? I tried using a MemoryStream as the underlying data store, but that didn't seem to work.
  • Is it possible to make the reader wait until the writer has completed writing?
  • Is it possible to detect that the writer is still writing?

Any of the above approaches would, I believe, solve my problem. It's not required that writing and reading happens simultaneously. Actually, I would be perfectly happy if I could simply tell the client requesting the XmlReader that the reader isn't ready yet, and it must try again later. However, that requires that there's a way to detect that the writer is still writing.

I have full control over the code that creates the XmlReader and XmlWriter instances, but I can't change the public API. I can use a string, a StringBuilder, a MemoryStream, or any other in-memory object that will get the job done, as underlying storage, and I can use any derived class of XmlReader and XmlWriter.

Is there any way to make this system thread-safe?

like image 413
Mark Seemann Avatar asked Apr 24 '14 18:04

Mark Seemann


Video Answer


1 Answers

Your best bet is probably to create custom classes that derive from XmlReader and XmlWriter. You can add a common synchronization object to them and use something like a ReadWriterLockSlim to coordinate reading and writing. You would have to determine in the writer class what you mean when you say it's "done" (disposed? done writing a single node even if it's not completely done? etc.)

You could then just make the methods in the reader block until writing is not in progress.

like image 93
Adam Robinson Avatar answered Oct 23 '22 18:10

Adam Robinson