绑定可以创建在WPF内存泄漏? [英] Can bindings create memory leaks in WPF?
问题描述
我是否需要解除的项目,如该项目,以消失,prevent内存泄漏?我想我只是有点担心,如果我重装和一个新的模板应用于控制,并在模板中存在一个绑定到外部的元素,可能是prevent模板被控制取得垃圾回收?
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
通过的PropertyDescriptor
AddValueChanged
法事件。这将导致CLR创建从的PropertyDescriptor
到对象
,并在大多数情况下,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.
由于绑定必须继续侦听的变化。此行为保持引用的PropertyDescriptor
和对象
之间活着的目标仍然是在使用中。这可能会导致在对象的内存泄漏
任何对象
来该对象
指,这包括数据绑定目标。
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.
所以,如果短期要绑定到一个的DependencyProperty
或 INotifyPropertyChanged的
对象,那么你应该没问题,否则像任何订阅事件,你应该取消您的绑定
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一种可能性,但也有少数快速测试后似乎同样给我,我将不得不潜水更深入地进行确认,所以我个人认为在< STRONG>可能固定在4.5:)
这篇关于绑定可以创建在WPF内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!