Pattern for implementing INotifyPropertyChanged?

你离开我真会死。 提交于 2019-12-21 00:53:09

问题


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;

Can someone explain to me the necessity of the var handler = PropertyChanged assignment prior to checking it for null versus directly checking PropertyChanged == null directly?

Thanks


回答1:


Eric Lippert explains this in details in this blog article: Events and races.

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)




回答2:


It's the thread safe method of raising events. By assigning the publicly accessible PropertyChanged event locally before using it you ensure that it won't be different between the 'if' statement and the line actually raising the event.




回答3:


In a multi-threaded world, the PropertyChanged may be set to null after the if statement has been evaluated.



来源:https://stackoverflow.com/questions/4461865/pattern-for-implementing-inotifypropertychanged

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!