7

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

skaffman
  • 398,947
  • 96
  • 818
  • 769
KyleLib
  • 774
  • 3
  • 9
  • 26
  • possible duplicate of [Why does C# require you to write a null check every time you fire an event?](http://stackoverflow.com/questions/3102918/why-does-c-require-you-to-write-a-null-check-every-time-you-fire-an-event) – decyclone Dec 16 '10 at 14:48
  • @decyclone, this isn't a dupe... The OP isn't asking why you must check if the handler is null, but why you need to use a local copy of the handler. – Thomas Levesque Dec 16 '10 at 14:55
  • Is this pattern necessary for VB.NET? Or does RaiseEvent handle this for you? – MCattle Feb 13 '14 at 19:06

3 Answers3

4

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)

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • It is up to the subscriber to handle the case where it is called just after it has been un-subscribed (whatever the event source does this race cannot be avoided without eliminating all concurrency). – Richard Dec 16 '10 at 14:59
1

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.

James Hay
  • 12,580
  • 8
  • 44
  • 67
0

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

John Sloper
  • 1,813
  • 12
  • 14