模式实施INotifyPropertyChanged的? [英] Pattern for implementing INotifyPropertyChanged?
问题描述
我已经看到用于实现INotifyPropertyChanged的以下模式
I have seen the following pattern used for implementing INotifyPropertyChanged
private void NotifyPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
有人能向我解释,在 VAR处理的必要性,检查它是否为null与直接检查之前=的PropertyChanged 分配的PropertyChanged == NULL 直接?
感谢
推荐答案
埃里克利珀解释了这本博客文章详细介绍:的Events和种族的。
Eric Lippert explains this in details in this blog article: Events and races.
基本上,这个想法是要避免出现竞争状况的情况下,另一个线程退订的最后一个处理此事件您检查后的PropertyChanged!= NULL
,但在此之前实际调用的PropertyChanged
。如果您在处理程序的本地副本,这是不可能发生的(但你可能最终会调用一个刚刚退订处理程序)
Basically, the idea is to avoid a race condition in case another thread unsubscribes the last handler for this event after you check PropertyChanged != null
, but before you actually invoke PropertyChanged
. If you make a local copy of the handler, this cannot happen (but you might end up calling a handler that's just been unsubscribed)
这篇关于模式实施INotifyPropertyChanged的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!