4

I'm developing some application, wich calls lot of XmlSerializer constructor with extraTypes parametr. I've find out, that each call encrease application memory for about 100KB and 2 descriptors (sometimes more). Code example:

this code encrease application memory for 100KB and 2 handlers per each call

while (true)
            {
                Console.ReadLine();
                new XmlSerializer(typeof (object), new Type[] {});
            }

this code encrease application memory for 43024KB and 2004 handlers

 for (var i = 0; i < 1000; i++)
            {
                new XmlSerializer(typeof (object), new Type[] {});
            }

so just siplest example of console application:

internal class Program
    {
        private static void Main(string[] args)
        {
            //this code encrease application memory for 43024KB and 2004 handlers
            for (var i = 0; i < 1000; i++)
            {
                new XmlSerializer(typeof (object), new Type[] {});
            }
            Console.WriteLine("Finished. Press any key to continue...");


            Console.ReadLine();
        }
    }

Is it a bug in XmlSerializer or im doing something wrong?

P.s. same with optimize code on and Release build

Timur Lemeshko
  • 2,747
  • 5
  • 27
  • 39
  • Duplicate of [Memory Leak using StreamReader and XmlSerializer](https://stackoverflow.com/questions/23897145/memory-leak-using-streamreader-and-xmlserializer) – dbc Aug 12 '16 at 20:47

1 Answers1

4

Ok, there is already an answer on msdn https://blogs.msdn.microsoft.com/tess/2006/02/15/net-memory-leak-xmlserializing-your-way-to-a-memory-leak/

Shot answer is: no, it is not a bug, it is a feature ;)

XmlSerializer creates a TempAssembly per each call of constructor with extraTypes parametr. And "an assembly is not an object on the GC Heap, the GC is really unaware of assemblies, so it won’t get garbage collected"

Solution is to cache XmlSerializer's in some dictionary and use only one object per type instead of creating new XmlSerializer each time u need it

Timur Lemeshko
  • 2,747
  • 5
  • 27
  • 39
  • Yep, another approach for you is to process your code in new AppDomain and unload appDomain after processing. Thus you'll get rid of this temp assemblies. Just debugged XmlSerializer and saw exactly what you've said in your answer, nice question – ams4fy Aug 11 '16 at 09:57