为什么使用这个构造 - PropertyChangedEventHandler handler = this.PropertyChanged?
文章 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
局部变量背后的原因是,在多线程环境中,在检查 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.
这样做是为了线程安全。在第二个示例中,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.
这是为了确保 OnPropertyChanged 方法是线程安全的。请参阅在事件处理程序中使用 null 检查进行其他讨论。
This is to ensure that the OnPropertyChanged method is thread safe. See Use of null check in event handler for another discussion.