问题
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