INotifyProperyChanged - why an additional assignment?

When implementing an interface INotifyPropertyChangedin its most basic form, most people seem to implement it as follows:

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

My question is: why an additional appointment var propertyChanged = PropertyChanged;? Is it just a matter of preference or is there a good reason for this? The following is undoubtedly true:

public virtual void OnPropertyChanged(string propertyName)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}
+5
source share
3 answers

Assigning a temporary variable removes the likelihood of a race condition between the zero check and the last event subscriber, canceling the subscription. See the .NET Event Guide here .

Snip:

    // Make a temporary copy of the event to avoid possibility of
    // a race condition if the last subscriber unsubscribes
    // immediately after the null check and before the event is raised.
    EventHandler<CustomEventArgs> handler = RaiseCustomEvent; 
+4
source

, - null .

, , .

+1

In a multi-threaded application, it is possible that (in the second example) between validation, to see if PropertyChanged != null(suppose that it is not null) and actually calls a delegate, your thread is pre-empted by another one by unregistering the last participant from the delegate. Then, when the original thread resumes and calls PropertyChanged(this, new PropertyChangedEventArgs(propertyName));, it will now be empty, and will be NullReferenceException.

+1
source

All Articles