简体   繁体   中英

Why does implementing INotifyPropertyChanged avoid memory leaks in WPF?

I read about how memory leaks can be avoided in Windows Presentation Foundation apps, by binding only properties that either implements INotifyPropertyChanged or they are DependencyObject objects. But how does that make the CLR to collect this objects?

Source info:

WPF Bindings can actually cause memory leaks. The rule of thumb is to always bind to a DependencyObject or to a INotifyPropertyChanged object. When you fail to do so, WPF will create a strong reference to your binding source (meaning the ViewModel) from a static variable, causing a memory leak ( https://michaelscodingspot.com/ways-to-cause-memory-leaks-in-dotnet/ )

If a property does not implement the INotifyPropertyChanged interface, then the WPF framework will stupidly add one for you by subscribing to the PropertyDescriptor.ValueChanged event. Since WPF and the CLR do not know when to dispose of / unsubscribe from the event, it holds on to the property forever. And since the property is being referenced, it can not be garbage collected. The whole instance of the class that contains that property stays in memory forever, thus causing a memory leak.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM