Are XmlSerializers ThreadSafe?
Here's the deal:
- It's expensive to make XmlSerializers (until .NET 2.0 when sgen.exe comes out and I can pre-created and compile Serializers.
- I made an XmlSerializer Factory:
public
class XmlSerializerFactory
{
private XmlSerializerFactory(){}
private static Hashtable serializers = new Hashtable();
public static XmlSerializer GetSerializer(Type t)
{
XmlSerializer xs = null;
lock(serializers.SyncRoot)
{
xs = serializers[t] as XmlSerializer;
if(xs == null)
{
xs = new XmlSerializer(t);
serializers.Add(t,xs);
}
}
return xs;
}
} -
This Factory is thread safe (right?) BUT Are XmlSerializer instances ThreadSafe? The MSDN Documentation gives the standard cop-out answer "They aren't explicitly Thread Safe..." (which means they weren't written to be, but also weren't written NOT to be)
So, to make sure I cover the case when someone is deserializing the same type of object using the SAME instance of a deserializer on multiple threads, I've been doing this:
XmlSerializer xs2 = XmlSerializerFactory.GetSerializer(
typeof(MyNamedType));lock(xs2)
{
mynameInstance = (MyNamedType)xs2.Deserialize(someStringReader);
}
Is the lock{} needed? Am I being paranoid? Mr. Purdy? Bueller?
About Scott
Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.
About Newsletter
But it's not being paranoid, I would do exactly the same. It won't hurt, unless the heart of your program is about serializing and deserializing objects...
Comments are closed.