XmlSerializer Madness: The Guts and the Conclusion
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.
About Newsletter
Comments are closed.
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.