System Reflection Runtime Assembly Leaks From Xml Serializer

I had this problem with windows service memory working set growing indefinitely during the lifetime of the process at customer site. The cause seems obvious in retrospective but I had no results from googling this at the time. Hopefully this record will turn up on google for people looking at a ballooning "System.Reflection.RuntimeAssembly" count and wondering what could be the cause.

Once I had a dump mailed me from customer that was prepared with the procdump -ma <process.id> command, I was able to open it with cdb and did a !DumpHeap -stat command:

<snip>

000007fee1221c70      145        43344 System.Collections.Hashtable+bucket[]
000007fee1219fe0     1378        66144 System.Reflection.RuntimeAssembly
000007fee1215940     1747        83856 System.RuntimeType
000007fee121ac30      978       210680 System.Object[]
000007fee1216728     3211       220480 System.String
Total 11143 objects
0:000>

Here it is obvious that the count of System.Reflection.RuntimeAssembly instances is suspiciously high: 1378. My first thought was that somehow the System.Assembly objects retrieved from System.Assembly.GetExecutingAssembly() method invocations were not disposed/closed properly, but that didn't seem to be the case and the documentation at MSDN was not suggesting anything to that tune.

I was then able to replicate the issue on my workstation by loading customer's configuration and found that the place where these instances are created is the XmlSerializer.FromTypes() method. MSDN confirms that: "If you use any of the other constructors, multiple versions of the same assembly are generated and never unloaded, which results in a memory leak and poor performance. The easiest solution is to use one of the previously mentioned two constructors." The other two constructors mentioned are:

With the culprit found the easy fix was to move the creation of XmlSerializer via XmlSerializer.FromTypes() to static initialization so it is invoked once per lifetime of AppDomain.


Published: 2012-05-15