Can bindings create memory leaks in WPF?

前端 未结 3 1063
醉酒成梦
醉酒成梦 2020-11-30 22:18

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 con

3条回答
  •  广开言路
    2020-11-30 22:26

    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.

    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.

    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.

    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


    Edit: 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 :)

提交回复
热议问题