c# - 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?
解决方案
Null 条件运算符大致相当于:
var handler = this.PropertyChanged;
if (handler != null)
{
handler(…);
}
它创建局部变量的部分?这将有助于线程安全。
但是,它不是 100% 可靠的。看,人们以前使用过这种模式。它一直为活动提供建议。但除非您标记handler
为volatile
,否则编译器或 JiT 编译器可能会因为未充分使用变量而将其删除。编译器自行设置它可能会阻止这种优化。
但归根结底,唯一可靠的是 lock 语句。
推荐阅读
- reactjs - 如何避免弹出组件中的自动关闭?
- python - 如何使用 nltk 将令牌列表转换为 wordnet 引理列表?
- angular - 在 angular2+ 中定义模型类的好处
- c++ - CMake - 无法链接共享库(子目录)
- solace - 使用 AMQP/qpid-proton 将 python dict 发布到 Solace 时出错
- ruby-on-rails - (Rails) 序列化列的字段_未填充数据
- model-view-controller - 如何将完整的 HTML 页面显示为 MVC 视图?
- android - getStringExtra 上的空指针异常
- css - CSS 过渡在 iOS 设备的 Chrome 上表现不同
- javascript - 覆盖节点服务器中的文件