views:

489

answers:

4

This article http://blogs.msdn.com/tess/archive/2006/02/15/532804.aspx by Tess Ferrandez outlines why using XMLSerialization can cause memory leaks.

The leak is a result of how the objects are instantiated in memory as assemblies, not objects so are not targeted by the Garbage Collector.

The article was originally written on the 1.0/1.1 CLR, but the updates are unclear about the 2.0 CLR.

I'm using XMLSerialization/Deserialization extensively in a web app still in beta for UI/server exchanges. The objects are just DTOs (objects with only properties).

Thank you in advance!

A: 

It is largely solved through the .NET 2.0 DynamicMethod. However, there's still a failure mode if you don't use the [XmlRoot] attribute. Review this article for details.

Hans Passant
Dynamic method does not fix the issue of assemblies being unloaded from an AppDomain. It only creates collectable methods.
JaredPar
As far as I understood in the article they still say that you might have memory leaks if you use any of the "special" constructors.
csgero
+1  A: 

I ran into the same issue with 2.0, so I can confirm the memory leak still exists there, but I have no experience with 3.5. As long as you only use the constructors XmlSerializer(type) and XmlSerializer(type, defaultNameSpace) you should be safe, as the XmlSerializers will be automatically cached. If you use any of the other constructors you'll have to create your own cache.

csgero
+2  A: 

The part that is actually causing the leak is that the assemblies generated by the XML engine for serialization purposes are not ever collected. As of CLR 2.0SP1 (.Net 3.5) this is still the case. Once an assembly is loaded into a process it will not be removed until the AppDomain containing that assembly is also unloaded.

If you notice at the bottom of the article though, she mentions a way to get the XML engine to reuse the assemblies so the memory won't grow out of control.

JaredPar
Are you sure that .NET 2.0 SP1 means .NET 3.5 ?
abatishchev
@abatishchev - .NET 3.5 uses CLR2.0 SP1...so yes
Kev
A: 

Thank you. It appears as though the key is to use XmlSerializer(type) and allow the in-memory instance to stay cached. It appears that if you alias the class name the cache doesn't work and the leaks ensue.. I will have to test and monitor to know for sure if we are leak-free. -Dustin

dustinson