Scott Hanselman

Are XmlSerializers ThreadSafe?

December 05, 2003 Comment on this post [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
Hosting By
Hosted in an Azure App Service
December 05, 2003 8:08
Only creating the first instance for a particular type is expensive after the first instance there is no overhead.
December 05, 2003 16:33
Only the guys who wrote XmlSerializer can tell you if it's really needed.
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.

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