Search code examples
c#propertychanged

Why use this construct - PropertyChangedEventHandler handler = this.PropertyChanged?


The article http://msdn.microsoft.com/en-us/magazine/dd419663.aspx has the following code sample:

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged(string propertyName)
{       
    PropertyChangedEventHandler handler = this.PropertyChanged;
    if (handler != null)
    {
        var e = new PropertyChangedEventArgs(propertyName);
        handler(this, e);
    }
}

My question is what is gained by introducing the variable 'handler' - the following code seems to work fine:

public event PropertyChangedEventHandler PropertyChanged;

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

Solution

  • The reasoning behind the local variable is that in a multi-threaded environment, the event could be devoid of subscribers (ie, become null) in the gap between checking for null and firing the event.

    By taking a local variable, you are avoiding this potential issue - checking the event in a thread-safe way. It does raise the issue that the event might be thrown for an item that had previously unhooked.