开发者

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

I was looking in the framework for an implementation of WeakEventManager that listens for changes开发者_StackOverflow 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜