首页 > 解决方案 > Why does the null-conditional operator promote thread-safety in C#?

问题描述

There's a modern idiom in C# that utilizes the null-conditional operator to promote thread-safety when using delegates. Namely:

Update?.Invoke(this, theArgs);

Why does this work? Does the C# specification guarantee atomicity in the operation? Does the null-conditional operator make an underlying copy of its operand before executing the Invoke() method?

标签: c#thread-safetynull-conditional-operator

解决方案


Null 条件运算符大致相当于:

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

它创建局部变量的部分?这将有助于线程安全。

但是,它不是 100% 可靠的。看,人们以前使用过这种模式。它一直为活动提供建议。但除非您标记handlervolatile,否则编译器或 JiT 编译器可能会因为未充分使用变量而将其删除。编译器自行设置它可能会阻止这种优化。

但归根结底,唯一可靠的是 lock 语句。


推荐阅读