Scott Hanselman

Are XmlSerializers ThreadSafe?

December 5, '03 Comments [2] Posted in Web Services | XmlSerializer
Sponsored By

Here's the deal:

  1. It's expensive to make XmlSerializers (until .NET 2.0 when sgen.exe comes out and I can pre-created and compile Serializers.
  2. 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;
        }
    }

  3. 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.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.