是C#的空条件委托调用线程安全的? [英] Is C#'s null-conditional delegate invocation thread safe?

查看:251
本文介绍了是C#的空条件委托调用线程安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我一直写事件养殖户;例如PropertyChanged的:

 公共事件PropertyChangedEventHandler的PropertyChanged; 
私人无效RaisePropertyChanged(字符串名称)
{
VAR处理器=的PropertyChanged;
如果(处理!= NULL)
处理器(这一点,新PropertyChangedEventArgs(名));
}

在最新的Visual Studio,然而,灯泡thingamabob建议简化了代码这个:

 私人无效RaisePropertyChanged(字符串名称)
{
的PropertyChanged .Invoke(这一点,新PropertyChangedEventArgs(名));
}



虽然我赞成简化我总是,我想肯定这是安全的。在我的原代码,我的处理程序分配给一个变​​量,以防止竞争条件,其中用户可能成为其设置在空检查和调用之间。在我看来,新的简化形式将遭受这种情况,但我想看看是否有人能证实或否认这一点。


解决方案
<从MSDN p>




新的方法是线程安全的,因为编译器只生成的代码
评价的PropertyChanged一次,保持结果
临时变量。你需要显式调用Invoke方法
,因为没有空条件委托调用语法
的PropertyChanged?(E)。有太多暧昧的解析情况
允许它。




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


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

这篇关于是C#的空条件委托调用线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆