Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is C#'s null-conditional delegate invocation thread safe? [duplicate]

This is how I have always written event raisers; for example 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 light bulb thingamabob suggested simplifying the code to this:

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

Although I'm always in favor of simplification, I wanted to be sure this was safe. In my original code, I assign the handler to a variable to prevent a race condition in which the subscriber could become disposed in between the null check and the invocation. It seems to me that the new simplified form would suffer this condition, but I wanted to see if anyone could confirm or deny this.

like image 287
amnesia Avatar asked Apr 05 '16 12:04

amnesia


1 Answers

It is as thread-safe as the code it replaced (your first example) because it is doing the exact same thing, just using a hidden variable.

like image 98
Lasse V. Karlsen Avatar answered Nov 14 '22 21:11

Lasse V. Karlsen