Search code examples
c#.netmultithreadingxml-parsingxmlschemaset

Is XmlSchemaSet allowed to be shared among multiple XmlReader/XmlWriter objects?


According to MSDN, XmlSchemaSet class is not guaranteed to be thread-safe.

So can multiple XmlReader objects be created with a single XmlReaderSettings object referencing one XmlSchemaSet object and used concurrently from multiple threads? Or does this mean I am required to create a new XmlReaderSettings object and assign it a new copy of XmlSchemaSet every time I need to process a new document in the background?

Seems like this would be very wasteful. Especially since XmlSchemaSet would need to recompile the schema for every new document.

Is the answer the same for XmlWriter objects?

Of course, I wouldn't modify the XmlSchemaSet object after populating it initially. I would also call the Compile method before first using it. After that, it seems like everything should be just safe since only reads would be performed, but I'm not sure.


Solution

  • If it says it isn't thread-safe, then (contractually) you can't share it / use it concurrently.

    Now it might work. But Microsoft are explicitly stating that it isn't guaranteed to work. So even if it works today, if may not work the next time you upgrade .NET Framework (for example).

    The usage of other types that aren't thread-safe at http://referencesource.microsoft.com/#System.Xml/System/Xml/Schema/XmlSchemaSet.cs (e.g. Hashtable) would mean I would strongly encourage you not to use XmlSchemaSet across threads. Using XmlSchemaSet across multiple threads may be OK if you are just reading (since Hashtable supports multiple readers, for example) - but XmlSchemaSet working across multiple threads isn't guaranteed for perpetuity (even if it does work today).