Scott Hanselman

XmlSerializer Madness: The Guts and the Conclusion

December 05, 2003 Comment on this post [1] Posted in XmlSerializer
Sponsored By

Looks like a little bit of wisdom from Kevin Dente has solved the mystery.

He sez:

A little Reflectoring into the XMLSerializer source shows that in .NET 1.1 it caches the temp assembly using both the type and default namespace as the key. However, 1.0 cached only on the type, and if you specified a namespace it ignored the cache. And it looks like even in 1.1 the other constructor overloads ignore the cache. Good to know.

And the reflectoring shows just that: (Note the Monitor.Enter [lock()] around their cache)

public XmlSerializer(Type type, string defaultNamespace){ 
  XmlReflectionImporter importer1;
  TempAssemblyCache cache1;
  this.events = 0;
  base..ctor();
  this.events.sender = this;
  this.tempAssembly = XmlSerializer.cache[defaultNamespace, type];
  if (this.tempAssembly == null){
    cache1 = XmlSerializer.cache;
    Monitor.Enter(XmlSerializer.cache);
    try{
       this.tempAssembly = XmlSerializer.cache[defaultNamespace, type];
       if (this.tempAssembly == null){
          importer1 = new XmlReflectionImporter(defaultNamespace);
          this.tempAssembly = XmlSerializer.GenerateTempAssembly(importer1.ImportTypeMapping(type));
          XmlSerializer.cache.Add(defaultNamespace, type, this.tempAssembly);
     }
}
finally{  Monitor.Exit(cache1); } } }

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 08, 2003 21:43
Hmm, this got me thinking. If you do use a constructor form that doesn't take advantage of the XmlSerializer's built in-cache, what happens to that temp assembly? Will it get garbage collected eventually? I know assemblies that are loaded from files never get unloaded until the appdomain unloads, but what happens with dynamic assemblies? I haven't found a good explanation of that.

In response to your original question, by my reading of the code it looks like the XmlSerializer is thread-safe. Do you agree? I may need to use the XmlAttributeOverrides version of the XmlSerializer, and it looks like it would be safe to cache a copy of that sucker in a static somewhere.

Comments are closed.

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