为什么使用这个构造 - PropertyChangedEventHandler handler = this.PropertyChanged?

发布于 2024-10-08 15:05:35 字数 845 浏览 1 评论 0原文

文章 http://msdn.microsoft.com/en-us/magazine/dd419663 .aspx 具有以下代码示例:

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged(string propertyName)
{       
    PropertyChangedEventHandler handler = this.PropertyChanged;
    if (handler != null)
    {
        var e = new PropertyChangedEventArgs(propertyName);
        handler(this, e);
    }
}

我的问题是通过引入变量“handler”获得什么 - 以下代码似乎工作正常:

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged(string propertyName)
{   
    if (PropertyChanged!= null)
    {
        var e = new PropertyChangedEventArgs(propertyName);
        PropertyChanged(this, e);
    }
}

The article http://msdn.microsoft.com/en-us/magazine/dd419663.aspx has the following code sample:

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged(string propertyName)
{       
    PropertyChangedEventHandler handler = this.PropertyChanged;
    if (handler != null)
    {
        var e = new PropertyChangedEventArgs(propertyName);
        handler(this, e);
    }
}

My question is what is gained by introducing the variable 'handler' - the following code seems to work fine:

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged(string propertyName)
{   
    if (PropertyChanged!= null)
    {
        var e = new PropertyChangedEventArgs(propertyName);
        PropertyChanged(this, e);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

墨小墨 2024-10-15 15:05:35

局部变量背后的原因是,在多线程环境中,在检查 null 和触发事件之间的间隙,事件可能没有订阅者(即变为 null)。

通过使用局部变量,您可以避免这个潜在的问题 - 以线程安全的方式检查事件。它确实提出了一个问题,即可能会为之前已脱钩的项目引发该事件。

The reasoning behind the local variable is that in a multi-threaded environment, the event could be devoid of subscribers (ie, become null) in the gap between checking for null and firing the event.

By taking a local variable, you are avoiding this potential issue - checking the event in a thread-safe way. It does raise the issue that the event might be thrown for an item that had previously unhooked.

放肆 2024-10-15 15:05:35

这样做是为了线程安全。在第二个示例中,PropertyChanged 的​​调用列表可能在 if 块期间变为 null,从而导致异常。

This is done for thread safety. In the second example is it possible that the invocation list of PropertyChanged could become null during the if block, resulting in an exception.

偏闹i 2024-10-15 15:05:35

这是为了确保 OnPropertyChanged 方法是线程安全的。请参阅在事件处理程序中使用 null 检查进行其他讨论。

This is to ensure that the OnPropertyChanged method is thread safe. See Use of null check in event handler for another discussion.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文