Article ID: 938416 - Last Review: July 26, 2007 - Revision: 1.1 A memory leak may occur when you use data binding in Windows Presentation FoundationOn This PageSYMPTOMSWhen you use data binding in Microsoft Windows Presentation Foundation (WPF), a memory leak may occur. CAUSEThis issue occurs if the following conditions are true:
WORKAROUNDTo work around this issue, use one of the following methods. Method 1Access property P through a DependencyProperty object.Method 2Expose the INotifyPropertyChanged interface on object X.Method 3Set the mode of the data binding to OneTime.STATUS This behavior is by design. MORE INFORMATIONIn WPF, a data-binding operation that is not marked as OneTime must listen for property change notifications from the source object (object X). WPF uses the built-in notifications of the DependencyProperties class or the notifications from the INotifyPropertyChanged interface. If the DependencyProperties class and the INotifyPropertyChanged interface are unavailable, WPF uses the ValueChanged event. This behavior involves calling the PropertyDescriptor.AddValueChanged method on the PropertyDescriptor object that corresponds to property P. Unfortunately, this action causes the common language runtime (CLR) to create a strong reference from this PropertyDescriptor object to object X. The CLR also keeps a reference to the PropertyDescriptor object in a global table. This behavior causes a reference chain to occur in the following order:
Workaround method 1 and workaround method 2 cause WPF to use one of the preferred notification mechanisms. Workaround method 3 instructs WPF not to listen for change notifications. All three workaround methods avoid creating the reference between the PropertyDescriptor object and object X. In the following code example, the conditions for the leak are created. The first condition in the "Cause" section is met because object X refers to the children of object X. These children include the binding target, and the binding target is the TextBlock element. The second condition in the "Cause" section is met because property P is not a DependencyProperty object, and object X does not implement the INotifyPropertyChanged interface. This behavior causes the UIElementCollection class and the TextBlock element not to be released. Additionally, the StackPanel container class is not released, because the UIElementCollection class contains a reference to the StackPanel container class. This behavior occurs even if the UIElementCollection class and the TextBlock element are removed from the main tree by using the following line of code:
| Article Translations
|
Back to the top
