为什么实施 INotifyPropertyChanged 可以避免 WPF 中的内存泄漏?
Why does implementing INotifyPropertyChanged avoid memory leaks in WPF?
我了解了如何在 Windows Presentation Foundation 应用程序中避免内存泄漏,方法是仅绑定实现 INotifyPropertyChanged 或 DependencyObject 对象的属性。但是,这如何使 CLR 收集这些对象?
来源信息:
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/)
如果一个属性没有实现INotifyPropertyChanged接口,那么WPF框架会傻傻地通过订阅PropertyDescriptor.ValueChanged事件为你添加一个。由于 WPF 和 CLR 不知道何时处理/取消订阅事件,它会永远保留 属性。由于 属性 正在被引用,因此无法对其进行垃圾回收。包含 属性 的 class 的整个实例永远保留在内存中,从而导致内存泄漏。
我了解了如何在 Windows Presentation Foundation 应用程序中避免内存泄漏,方法是仅绑定实现 INotifyPropertyChanged 或 DependencyObject 对象的属性。但是,这如何使 CLR 收集这些对象?
来源信息:
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/)
如果一个属性没有实现INotifyPropertyChanged接口,那么WPF框架会傻傻地通过订阅PropertyDescriptor.ValueChanged事件为你添加一个。由于 WPF 和 CLR 不知道何时处理/取消订阅事件,它会永远保留 属性。由于 属性 正在被引用,因此无法对其进行垃圾回收。包含 属性 的 class 的整个实例永远保留在内存中,从而导致内存泄漏。