Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern for implementing 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;

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

like image 688
KyleLib Avatar asked Dec 16 '10 14:12

KyleLib


People also ask

How do you implement INotifyPropertyChanged?

To implement INotifyPropertyChanged you need to declare the PropertyChanged event and create the OnPropertyChanged method. Then for each property you want change notifications for, you call OnPropertyChanged whenever the property is updated.

What is INotifyPropertyChanged in C#?

The INotifyPropertyChanged interface is used to notify clients, typically binding clients, that a property value has changed. For example, consider a Person object with a property called FirstName .

What is property changed?

The PropertyChanged event can indicate all properties on the object have changed by using either null or String. Empty as the property name in the PropertyChangedEventArgs.


2 Answers

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)

like image 143
Thomas Levesque Avatar answered Oct 22 '22 10:10

Thomas Levesque


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.

like image 36
James Hay Avatar answered Oct 22 '22 08:10

James Hay