Are there still known memory leaks with XMLSeriali

2019-05-01 21:41发布

问题:

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!

回答1:

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.



回答2:

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.



回答3:

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.



回答4:

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