Do I have a memory leak in my WPF Navigation? Do I have a memory leak in my WPF Navigation? wpf wpf

Do I have a memory leak in my WPF Navigation?


Yes, according to what you've provided, you have a memory leak. When you found the references chain, and it's not in your code, the easiest way to go would be... Reflector.

Image says: JournalEntryKeepAlive._keepAliveRoot field holds a reference to the object. Let's go in Reflector and see how this guy is hooked with our object.

This time it was easy, and all traces lead to NavigationService.MakeJournalEntry() function and then to NavigationService.IsContentKeepAlive(). Here it is:

internal bool IsContentKeepAlive(){    bool keepAlive = true;    DependencyObject dependencyObject = this._bp as DependencyObject;    if (dependencyObject != null)    {        keepAlive = JournalEntry.GetKeepAlive(dependencyObject);        if (!keepAlive)        {            PageFunctionBase base2 = dependencyObject as PageFunctionBase;            bool flag2 = !this.CanReloadFromUri;            if ((base2 == null) && flag2)            {                keepAlive = true;            }        }    }    return keepAlive;}

Now you know the rules. Object is kept in memory if:

  • It's not a dependency object;
  • Attached propery JournalEntry.KeepAlive is true;
  • It's not a PageFunction and it can't be reloaded from Uri.

After this investigation it may be worth reading more about JournalEntry.KeepAlive property on MSDN.

This strategy helped me to find many memory-related insects. Hope it helps you too :).

PS: If you keep having problem with finding this particular leak, you could paste minimal code sample for us to reproduce it and give you more proper answer.

Cheers,Anvaka


I had the same problem and the same chart with Ants memory analyzer.The application used a NavigationWindow to host some WPF Pages and the navigation was made with this codebehind:

NavigationService.Navigate( new Page1());

The problem was created by multiple pages kept in memory by the journal and that couldn't be garbage collected.

What i did was to replace the NavigationWindow with a normal window, the Pages with UserControls and swap user controls inside the window, like they are pages.There are many examples on how to do this in google.After removing all the NavigationService.Navigate calls, i could finally garbage collect all the closed pages with Ants memory profiler.