Is C # delegate call flow safe?

This is how I always wrote event raiders; e.g. PropertyChanged:

    public event PropertyChangedEventHandler PropertyChanged;
    private void RaisePropertyChanged(string name)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(name));
    }

In the latest Visual Studio, however, the thingamabob light bulb suggested simplifying the code:

    private void RaisePropertyChanged(string name)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }

Although I always support simplification, I wanted to make sure it was safe. In my source code, I assign a variable handler to prevent a race condition in which a subscriber can be removed between a zero check and a call. It seems to me that the new simplified form will suffer from this condition, but I would like to know if anyone can confirm or deny it.

+4
source share
3 answers

from MSDN:

, PropertyChanged , . Invoke PropertyChanged? (). .

https://msdn.microsoft.com/en-us/library/dn986595(v=vs.140).aspx

+5

, ( ), , .

+7

.net framework interlock.CompareExchange, . , . , Volatile.Read ( )

Volatile.Read(ref PropertyChanged)?. Invoke ( PropertyChangedEventArgs ())

Source: CLR via C #

Another source: https://codeblog.jonskeet.uk/2015/01/30/clean-event-handlers-invocation-with-c-6/

0
source

All Articles