XmlSerializer extraTypes memory leak

雨燕双飞 提交于 2019-12-04 03:44:05

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/38892352/xmlserializer-extratypes-memory-leak

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!