Strange wpf memory leak

2019-02-19 19:36发布

问题:

I'm having a wierd problem with a memory leak through a MenuItem in wpf.

I can observe this memory leak in .net memory profiler.

Our application has the following architecture:

A MainWindow which data templates an ApplicationPresenter. ApplicationPresenter lasts for the entire lifetime of the application. ApplicationPresenter has a MainPresenter which essentially represents a file and its contents. When a file (Solution) is loaded a new main presenter is created and the old one thrown away.

The data template for the application presenter looks like this:

    <DataTemplate DataType="{x:Type ApplicationPresenter}">
        <ContentPresenter Content="{Binding Presenter}"/>
    </DataTemplate>

MainPresenter has a number of tabs but basically its data template is a a big Menu inside a DockPanel. The menu has some nested elements eg File, Edit, View ... across the top and within File you have New, Open ... and then sub menus such as Import which then has a load of items itself.

All of these presenters implement INotifyPropertyChanged and we have an implementation of ICommand that gets around the crazyness associated with that (in general commands dont leak in the application).

However what I see is that when opening a new solution (or any other operation that creates a new MainPresenter) is that the original MainPresenter (the first one that is created when the application loads) hangs around in memory through the field _submenuPopup of MenuItem! I've attached the picture from the profiler to help show what I mean:

graph of leak

The number of instances doesnt go past two when doing more operations and it is always the first Presenter that is in memory. The menus all work (including the items in the sub menus)

Is anyone familiar with this problem and know of a way to solve it?

Its not massively critical as only one solution meaning its not going to lead to an OutOfMemoryException. However it can be quite expensive as the program can be opened by double clicking files (meaning the first presenter can hold on to a large amount of data), potentially doubling the memory usage unecessarily.