Template for implementing INotifyPropertyChanged?

I saw the following template used to implement 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 need to assign var handler = PropertyChanged before checking it for null or directly for checking PropertyChanged == null ?

thanks

+6
inotifypropertychanged
source share
3 answers

Eric Lippert explains this in detail in this blog post: Events and Races .

Basically, the idea is to avoid a race condition if another thread unsubscribed from the last handler for this event after checking PropertyChanged != null , but before you actually call PropertyChanged . If you create a local copy of the handler, this cannot happen (but you can end up calling the handler that has just been canceled)

+4
source share

This is a thread safe method of raising events. By assigning a publicly accessible PropertyChanged event locally before using it, you will make sure that it does not differ from the "if" operator and the line that actually raises the event.

+1
source share

In a multi-threaded world, the PropertyChanged property can be set to null after the if statement has been processed.

0
source share

All Articles