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:
XmlWriter
instance and starts writingXmlReader
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?
MemoryStream
as the underlying data store, but that didn't seem to work.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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With