Firedragon
Firedragon

Reputation: 3733

Is NotifyPropertyChanged thread safe?

I am looking at NotifyPropertyChanged() from INotifyPropertyChanged and noticed that in the examples from Microsoft such as here:

http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx

There is no capturing of the delegate reference first (as it says to do here for example: Use of null check in event handler)

I had a look in the auto-generated Reference.cs for my ServiceReferences and this check is done.

So my question is should I be doing this (in whatever form such as extension methods etc)? Are there any possible issues if I don't?

Upvotes: 4

Views: 1120

Answers (1)

Ray
Ray

Reputation: 46565

You're right, the check should be done and their example is wrong.

Below is the standard code.

private void NotifyPropertyChanged(String propertyName)
{
    var handler = PropertyChanged;
    if (handler != null)
    {
        handler (this, new PropertyChangedEventArgs(propertyName));
    }
}

Edit: A further explanation about why this is needed (and why it works)

In the MS example they do a null check directly on PropertyChanged and then invoke it. So it would be possible for PropertyChanged to become null between the null check and the invocation. By assigning the delegate to a local variable, we can ensure that we retain a reference to the delegate and it can't change between the null check and invocation.

Upvotes: 7

Related Questions