如前所述 here , PropertyChangedEventManager
类(class)
Provides a WeakEventManager implementation so that you can use the "weak event listener" pattern to attach listeners for the PropertyChanged event.
订阅属性更改有两种方式:
void AddHandler (INotifyPropertyChanged source, EventHandler<PropertyChangedEventArgs> handler, string propertyName)
void AddListener (INotifyPropertyChanged source, IWeakEventListener listener, string propertyName)
他们最终都调用了相同的方法:
private void AddListener(INotifyPropertyChanged source, string propertyName, IWeakEventListener listener, EventHandler<PropertyChangedEventArgs> handler)
与
listener
或 handler
设置为空。我需要使用强事件处理程序(即
source.PropertyChange += handler;
)更改一些代码以遵循弱模式。使用 AddHandler
这很简单方法。有什么理由更喜欢AddListener
(这需要我实现 IWeakEventListener
)?如果我要编写新代码,选择其中一种的原因是什么?
最佳答案
AddHandler(...
只是 .Net 4.5 的一个特性,它可以简化您的代码以应对常见情况。因此,如果满足要求,则是更好的选择。
在 .Net4.5 之前只有:
AddListener(...
您可以在以下来源中找到更多信息:... it is no longer necessary to create custom WeakEventManager or implement IWeakEventListener...
In WPF 4.5 RC, weak event pattern is improved. In addition to listeners, WeakEventManagers also support Handlers. The handlers are defined like event handlers but our classes don't need to implement a particular interface. Plus since there are no hard references maintained, there are no possible memory leaks.
边注:
根据我的经验,这些解决方案并不是万无一失的,如果您或您的团队中的某个人使用 lambda 表达式作为处理程序,您仍然可能会出现内存泄漏。
使用 lambda 表达式时,编译器生成匿名类作为目标(新生成的类包装 lambda 表达式)。
GC 会立即收集对此类的弱引用。
这里是 Thomas Levesque explanation :
Special case: anonymous method handlers If you're subscribing to the event with an anonymous method (e.g. a lambda expression), make sure to keep a reference to the handler, otherwise it will be collected too soon...
p.s 我最终使用了与 Thomas Levesque 类似的方法解决方案,并保护团队免于向 lambda 注册,我检查(通过反射)每个处理程序是否是匿名方法。如果是,我会抛出异常 - 所以开发人员立即知道这是 Not Acceptable ,并更改他们的代码。
关于c# - PropertyChangedEventManager : AddHandler vs AddListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52092516/