Is the Null-Conditional Operators thread-safety save from compiler optimisations? [duplicate]

浪子不回头ぞ 提交于 2020-03-28 06:53:10

问题


The documentation says that

PropertyChanged?.Invoke(…)

is thread safe, because it is equivalent to this:

var handler = this.PropertyChanged;
if (handler != null)
{
    handler(…);
}

Which has a little problem. Because that code has not been thread safe in the past. It seems on a glance, but compiler optimizations dealing with culling of underused temporary variables, could cut handler out entirely. Resulting in this actual code:

if (this.PropertyChanged != null)
{
    this.PropertyChanged(…);
}

Which is very much not thread safe..

To guarantee thread safety, you had to mark handler as volatile. As volatile tells the Compile Time and JiT Compilers "do not try to optimize anything about that variable, you just get in my way". But the equivalent code listed is exactly not this:

volatile var handler = this.PropertyChanged;
if (handler != null)
{
    handler(…);
}

So what am I missing here? Is the documentation somewhat wrong for omitting volatile? Is the variable handler safe from optimizations, if it is put there by the compiler? Is var marked implicitly volatile? Was "underused variable detection" made less aggressive with null checks? Something else?

来源:https://stackoverflow.com/questions/60679273/is-the-null-conditional-operators-thread-safety-save-from-compiler-optimisations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!