绑定会在 WPF 中造成内存泄漏吗? [英] Can bindings create memory leaks in WPF?

查看:28
本文介绍了绑定会在 WPF 中造成内存泄漏吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是否需要在物品消失时解除绑定以防止内存泄漏?我想我只是有点担心,如果我重新加载并将新模板应用于控件,并且在该模板中存在与外部元素的绑定,是否会阻止为模板制作的控件被垃圾收集?

Do I need to unbind items as the item disappears in order to prevent memory leaks? I guess I'm just a little worried that if I reload and a new template is applied to a control, and in that template there exists a binding to an outside element, could that prevent the control made for the template from being garbage collected?

推荐答案

如果您没有绑定到 DependencyProperty 或实现 INotifyPropertyChanged 的对象,则绑定可能会泄漏内存,完成后必须解绑.

If you are not binding to a DependencyProperty or a object that implements INotifyPropertyChanged then the binding can leak memory, and you will have to unbind when you are done.

这是因为如果对象不是 DependencyProperty 或者没有实现 INotifyPropertyChanged 那么它会通过 使用 ValueChanged 事件PropertyDescriptors AddValueChanged 方法.这会导致 CLR 创建一个从 PropertyDescriptorobject 的强引用,并且在大多数情况下,CLR 将保留对 PropertyDescriptor 的引用.一个全局表.

This is because if the object is not a DependencyProperty or does not implement INotifyPropertyChanged then it uses the ValueChanged event via the PropertyDescriptors AddValueChanged method. This causes the CLR to create a strong reference from the PropertyDescriptor to the object and in most cases the CLR will keep a reference to the PropertyDescriptor in a global table.

因为绑定必须持续监听变化.此行为使 PropertyDescriptorobject 之间的引用保持活动状态,因为目标仍在使用中.这会导致 object 和任何 object 引用的 object 内存泄漏,这包括数据绑定目标.

Because the binding must continue to listen for changes. This behavior keeps the reference alive between the PropertyDescriptor and the object as the target remains in use. This can cause a memory leak in the object and any object to which the object refers, This includes the data-binding target.

简而言之,如果您绑定到 DependencyPropertyINotifyPropertyChanged 对象,那么您应该没问题,否则像任何订阅的事件一样,您应该取消订阅您的绑定

So in short if you are binding to a DependencyProperty or INotifyPropertyChanged object then you should be ok, otherwise like any subscribed event you should unsubscribe your bindings

这有可能在 .NET4.5 中使用弱事件/引用修复,但经过几次快速测试后,我觉得还是一样,我将不得不更深入地进行确认,所以我会亲自在 可能在 4.5 中修复:)

There is a possibility this was fixed in .NET4.5 using Weak Events/References, But after a few quick tests it seemed the same to me, I will have to dive in more deeply to confirm, so I'll personally say in might be fixed in 4.5 :)

这篇关于绑定会在 WPF 中造成内存泄漏吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆