Memory Leak using StreamReader and XmlSerializer

前端 未结 6 2112

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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 06:08

    First off, you should be disposing of your StreamReader even if an exception is thrown (same for XMLObj). Use the using statement. Currently you will not dispose when an exception is thrown.

    It is very unlikely that you have a memory leak. More likely, the runtime simply did not elect to collect memory yet. Even GC.Collect will not necessarily cause memory to be released.

    I have run into similar situations when processing very large XML files (multi-GB). Even though the runtime grabs most available memory, it does release it when memory pressure warrants.

    You can use the memory profiler in Visual Studio to see what memory is allocated, and in what generation it resides.

    UPDATE

    The comment from @KaiEichinger is worth investigating. It indicates that the XmlSerializer may be creating a new cached object definition for every loop iteration

    XMLSerializer constructor creates the temporary assembly for the type to be serialized using reflection and since code generation is expensive the assembly is cached in the memory on per type basis. But many times root name will be changed and can be dynamic and it will not cache the dynamic assembly. So whenever the above line of code is called it loads the new assembly every time and will stay in the memory until AppDomain is unloaded.

提交回复
热议问题