4

I want to cache a single instance of DataContractSerializer to be used by multiple threads simultaneously to avoid the penalty of instantiating the serializer multiple times for the same root type. Each thread is going to be serializing a different object, but the DataContractSerializer object itself will be shared. (I'm not going to use IDataContractSurrogate or DataContractResolver, which evidently are related to more complex/formal XML/XSD schemas.)

Will I be OK?

In MSDN under "Thread Safety" for System.Runtime.Serialization.DataContractSerializer, it says:

Instances of this class are thread safe except when the instance is used with an implementation of the IDataContractSurrogate or DataContractResolver.

I find this a little vague (as is typical of the MSDN thread safety guidance) but it seems to indicate that my use case is appropriate. Bonus if you can point to personal experience, a unit test, or a framework disassembly that demonstrates it :)

P.S. I don't think this is a duplicate of Is WCF's DataContractSerilaizer thread safe? because that person's issue turned out to be unrelated to the thread safety of the DataContractSerializer itself.

Community
  • 1
  • 1
Jordan Rieger
  • 3,025
  • 3
  • 30
  • 50
  • 1
    You can't use a unit test or personal experience to demonstrate something is thread safe. You can use it to prove that something **isn't** thread safe, but not necessarily on demand :) – Marc Gravell May 24 '13 at 21:57
  • Hard to tell, it scattered all over the place. There's just no point in saving a copy of kilobytes when you burn a megabyte on a thread. – Hans Passant May 24 '13 at 23:30
  • @MarcGravell I suppose in *theory* one cannot prove thread safety with a unit test, ultimately due to some Turing halting/completeness problem. But in my experience most thread safety issues seem to be reproducible with a unit test that does a few minutes of really intense multi-threading and knows what kind of corruption to look for. I was just hoping someone would already know and save me the trouble of writing the tests (or reading the framework disassembly) myself :) – Jordan Rieger May 25 '13 at 00:22
  • @HansPassant It's not about saving memory, it is about saving the significant costs of initializing a DataContractSerializer. That costs especially hurt when deserializing many small junks of xml. – Stefan Sieber Aug 25 '15 at 06:53

1 Answers1

2

Yes your use case is appropriate. The implementations for both DataContractResolver and IDataContractSurrogate are done by the user of the DataContractSerializer. If you didn't implement and configure them, there are no threading issues (otherwise the MSDN documentation would be plain wrong).

I would even go further and assume that MSDN only ruled out the use of DataContractResolver and IDataContractSurrogate because they could be done in the wrong way (i.e. not thread safe). But there's unfortunately no evidence in documentation for that.

Stefan Sieber
  • 483
  • 4
  • 7