问题
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