문제

The boiler plate OnPropertyChanged code that you will likely see in almost any databinding example is as follows

public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{    
    PropertyChangedEventHandler handler = PropertyChanged;
    if(handler!=null)
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

Isn't this redundant though? Wouldn't it be easier to say this

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {    
         if(PropertyChanged!=null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

I am sure there is a reason why we do this I just can't find it.

올바른 솔루션이 없습니다

다른 팁

Using the second implementation it's possible for another thread to remove the only remaining event handler after the null check passes but before the delegate is invoked, resulting in a null referee exception. By copying the delegate before the check (delegates are immutable, removing a handler means assigning a new delegate, not mutating the existing one) means that such a NRE isn't possible. What is possible however is to invoke a handler after is has been removed, which can also cause problems.

If you know that the event will not have handlers added/removed from a thread other than the thread firing the event, then the two are equivalent.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top