Prevent memory leaks in WPF

2020-02-02 10:59发布

问题:

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)?

回答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.



回答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.



回答3:

Some helpful links on WPF resource dictionary leaks:

  • DynamicResource\StaticResource cause memory leaks
  • Memory leak problem with ResourceDictionary and MergedDictionaries


回答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