Things I did not know about garbage collection

posted in: Development | 0

I thought I knew all there was to know about garbage collection. You walk around the house, collecting garbage and then throw it into the waste cans that are taken to the curb every week. Then you have children, and force them to do the very same thing. Boy was I wrong! Apparently in .NET, the garbage man can refuse to pick up your refuse…

In some of my recent xml serialization code, I had a line of code that looked like this:

XmlSerializer serializer = new XmlSerializer(

typeof( T ),

new XmlRootAttribute { ElementName = rootElementName }


It was determined that this line was causing a memory leak – which seemed weird as the code itself is pretty innocuous. I stumbled upon this blog post from Tess Ferrandez which had an interesting tidbit:

If we take a look at the XmlSerializer constructor with Reflector we find that it calls:

this.tempAssembly = XmlSerializer.GenerateTempAssembly (







which generates a temp (dynamic) assembly. So every time this code runs (i.e. every time the page is hit) it will generate a new assembly. The reason it generates an assembly is that it needs to generate functions for serializing and deserializing and these need to reside somewhere. Ok, fine… it creates an assembly, so what? When we’re done with it, it should just disappear right?  Well… an assembly is not an object on the GC heap, the GC is really unaware of assemblies, so it won’t get garbage collected. The only way to get rid of assemblies in 1.0 and 1.1 is to unload the app domain in which it resides.

And therein lies the problem Dr Watson.

WHAT?? To quote the late great Johnny Carson, “I did not know that”.

I incorrectly assumed any object created within a method would just get picked up by the garbage collector during the next run. You learn something new every day.

Leave a Reply