Prevent memory leaks in WPF

11,719

Solution 1

This blog post lists the most common situations that cause memory leaks in WPF applications.

  • Event handlers to objects in parent windows
  • Registering to events from static objects
  • Using timers
  • Data binding
  • Changing the Text property of a text box

It also describes how to fix these common issues.

Another good approach is to develop an app while following the standard guidelines and then use some kind of profiler to determine any memory leaks or performance bottlenecks.

Solution 2

From MSDN: Any WPF framework-level element (those objects deriving from either FrameworkElement or FrameworkContentElement) has three common lifetime events: Initialized, Loaded, and Unloaded.

.....

Unloaded is raised last and is initiated by either the presentation source or the visual parent being removed. When Unloaded is raised and handled, the element that is the event source parent (as determined by Parent property) or any given element upwards in the logical or visual trees may have already been unset, meaning that data binding, resource references, and styles may not be set to their normal or last known run-time value.

Solution 3

Some helpful links on WPF resource dictionary leaks:

Solution 4

Watch out for events: it's very easy to miss something, because all references from the delegate will exist until the delegate lives. I suggest to use weak event pattern when it's possible. Actually Microsoft uses it in their Prism framework.

http://msdn.microsoft.com/en-us/library/aa970850.aspx

Also check out an issue that I was catched by many times when learning WPF http://support.microsoft.com/kb/938416/en-us

Share:
11,719

Related videos on Youtube

Miklós Balogh
Author by

Miklós Balogh

Updated on June 04, 2022

Comments

  • Miklós Balogh
    Miklós Balogh almost 2 years

    Working with WinForms you have to free memory after using gdi objects, event handlers, objects from native code, etc.

    In WinForms I used to remove for example event handlers in the dispose method.

    What is the best workaround to prevent memory leaks in Wpf? Is it the same as in Winforms using Dispose pattern? At all, do I have to care about event handlers, gdi objects in Wpf? What about the runtime created resources(Brushes, etc)?

    • John Smith
      John Smith
      Did you use deleaker or valgrind?
  • Solaiman Mansyur
    Solaiman Mansyur over 12 years
    Sorry it's an old link and may have been taken down. Searching for lazily hydrated resources and WPF might give some good results though.