简体   繁体   中英

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

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.

它与它替换的代码(你的第一个例子)一样是线程安全的,因为它只是使用一个隐藏变量做同样的事情。

from MSDN:

The new way is thread-safe because the compiler generates code to evaluate PropertyChanged one time only, keeping the result in temporary variable. You need to explicitly call the Invoke method because there is no null-conditional delegate invocation syntax PropertyChanged?(e). There were too many ambiguous parsing situations to allow it.

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

Internally .net framework uses interlock.CompareExchange when you subscribe for an event. This means you already has memory barrier there. To be thread safe you need to use Volatile.Read when accessing your event handler (it applies implicit aquire memory barrier)

Volatile.Read(ref PropertyChanged)?.Invoke(this, new PropertyChangedEventArgs(name))

Source: CLR via C#

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM