c# - PropertyChangedEventManager : AddHandler vs AddListener

标签 c# wpf events inotifypropertychanged

如前所述 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)

listenerhandler设置为空。

我需要使用强事件处理程序(即 source.PropertyChange += handler; )更改一些代码以遵循弱模式。使用 AddHandler 这很简单方法。有什么理由更喜欢AddListener (这需要我实现 IWeakEventListener )?

如果我要编写新代码,选择其中一种的原因是什么?

最佳答案

AddHandler(...
只是 .Net 4.5 的一个特性,它可以简化您的代码以应对常见情况。
因此,如果满足要求,则是更好的选择。
在 .Net4.5 之前只有:
AddListener(...
您可以在以下来源中找到更多信息:
  • Book - Introducing .NET 4.5 :

  • ... it is no longer necessary to create custom WeakEventManager or implement IWeakEventListener...


  • Blog post - Weak event pattern improvements :

  • 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/

    相关文章:

    java - 将所有按键事件转发到父 JFrame

    c# - HttpResponseMessage 在使用 HttpClient 时缺少 header ,但 fiddler 找到了

    c# - 使用属性网格修改窗体属性

    wpf - 将 XML 数据绑定(bind)到 WPF TreeView 控件

    WPF 文本框 VerticalContentAlignment 不工作

    c# - 通过反射查找事件 C#

    c# - 如何取消任务使其停止

    c# - 如何将文件夹复制到 U 盘? C#

    c# - wpf DataGrid 列索引未保存

    Silverlight 控件禁用/删除事件