Should I use weak event listeners while listening to DependencyProperty changes?

1k Views Asked by At

I was looking in the framework for an implementation of WeakEventManager that listens for changes to DependencyProperties. I'm a bit confused by the fact that the only weak property change event listener I find, the PropertyChangedEventManager, is designed to be used on types that implement INotifyPropertyChanged.

Does this mean that if you listen to a DependencyProperty for changes

DependencyPropertyDescriptor
    .FromProperty(target, target.OwnerType)
    .AddValueChanged(component, handler)

that I don't have to worry about leaking instances who are kept alive by event registration?

1

There are 1 best solutions below

2
On BEST ANSWER

DependencyPropertyDescriptor leaks big time, I had lot of issues because of it. Unless you explicitly call RemoveValueChanged all your components will be rooted. Internally it maintains a HashTable of EventHandler. Here is what it does:

if (this.valueChangedHandlers == null)
  this.valueChangedHandlers = new Hashtable();
EventHandler eventHandler = (EventHandler) this.valueChangedHandlers[component];
this.valueChangedHandlers[component] = (object) Delegate.Combine((Delegate) eventHandler, (Delegate) handler);

Since property descriptors are cached, all your components will be rooted.