Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top