Memory Leak using StreamReader and XmlSerializer

前端 未结 6 2057

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:08

    The leak is here:

    new XmlSerializer(typeof(XMLObj), new XmlRootAttribute("rootNode"))
    

    XmlSerializer uses assembly generation, and assemblies cannot be collected. It does some automatic cache/reuse for the simplest constructor scenarios (new XmlSerializer(Type), etc), but not for this scenario. Consequently, you should cache it manually:

    static readonly XmlSerializer mySerializer =
        new XmlSerializer(typeof(XMLObj), new XmlRootAttribute("rootNode"))
    

    and use the cached serializer instance.

提交回复
热议问题