Memory Leak using StreamReader and XmlSerializer

前端 未结 6 1992

I\'ve been googling for the past few hours and trying different things but can\'t seem to the bottom of this....

When I run this code, the memory usage continuously

6条回答
  •  盖世英雄少女心
    2020-11-22 06:05

    From MSDN:enter link description here

    To increase performance, the XML serialization infrastructure dynamically generates assemblies to serialize and deserialize specified types. The infrastructure finds and reuses those assemblies. This behavior occurs only when using the following constructors:

    XmlSerializer.XmlSerializer(Type)

    XmlSerializer.XmlSerializer(Type, String)

    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. Otherwise, you must cache the assemblies in a Hashtable, as shown in the following example.

    => So to fix it you have to use this constructor XmlSerializer xml = new XmlSerializer(typeof(XMLObj)) instead of XmlSerializer xml = new XmlSerializer(typeof(XMLObj), new XmlRootAttribute("rootNode"));

    and add root XML attribute into XMLObj class.

    [Serializable()]
    [XmlRoot("root")]
    public class XMLObj: IDisposable
    {
        [XmlElement("block")]
        public List nodes{ get; set; }
    
        public XMLObj() { }
    
        public void Dispose()
        {
            nodes.ForEach(n => n.Dispose());
            nodes= null;
    
            GC.SuppressFinalize(this);
        }
    }
    

提交回复
热议问题