Do I have a memory leak in my WPF navigation?

I am looking at a WPF application looking for a memory leak (using ANTS Memory Profiler 5.1), and I can see that some pages and controls take up memory when they shouldn't be.

So, I go to the graph of storing objects and see that it supports them, and I see this for each page:

Schedule of storage of objects http://img683.imageshack.us/img683/3013/ants.jpg

The fact is that KeepAlive is set to false on every page, and I don't think that such a property exists in user controls.

Can someone tell me what I should look for? Is this even a memory leak, or is this normal behavior for a WPF application?

+6
memory-leaks wpf
source share
2 answers

Yes, according to what you provided, you have a memory leak. When you find a link chain, and this is not in your code, the easiest way would be ... Reflector.

The image says: the JournalEntryKeepAlive._keepAliveRoot field contains a reference to the object. Release Reflector and see how this guy is attached to our object.

This time it was easy, and all traces lead to the NavigationService.MakeJournalEntry() function, and then to the NavigationService.IsContentKeepAlive() . Here he 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. An object is stored in memory if:

  • It is not an object of dependence;
  • The attached JournalEntry.KeepAlive property is true;
  • This is not a PageFunction, and it cannot be reloaded from Uri.

After this study, it might be worth reading more about the JournalEntry.KeepAlive property on MSDN.

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

PS: If you have a problem finding this particular leak, you can insert a minimal sample code so that we can reproduce it and give you a more correct answer.

Cheers, Anvaka

+8
source share

I had the same problem and the same diagram with the Ants memory analyzer. The application used NavigationWindow to host some WPF pages, and navigation was made with this entry:

 NavigationService.Navigate( new Page1()); 

The problem was created by several pages stored in the memory of the magazine, and it was impossible to collect garbage.

What I did was replace NavigationWindow regular window, pages with UserControls and change user controls inside the window, for example, these are pages. There are many examples of how to do this on Google. After deleting all the calls to NavigationService.Navigate I could finally remove the garbage to collect all the closed pages with the Ants memory profiler.

+5
source share

All Articles