Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    }
}
like image 727
sturdytree Avatar asked Dec 20 '10 12:12

sturdytree


2 Answers

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.

like image 50
Adam Houldsworth Avatar answered Oct 04 '22 21:10

Adam Houldsworth


This is done for thread safety. In the second example is it possible that the invocation list of PropertyChanged could become null during the if block, resulting in an exception.

like image 32
MattDavey Avatar answered Oct 04 '22 21:10

MattDavey