【问题标题】:Avoid race condition ?. operator避免竞争条件?操作员
【发布时间】:2017-10-04 12:19:21
【问题描述】:

可用于调用委托或事件的 ?. 运算符是否避免了竞争条件?

例如。手动避免竞争条件:

//The event-invoking method that derived classes can override.
        protected virtual void OnShapeChanged(ShapeEventArgs e)
        {
            // Make a temporary copy of the event to avoid possibility of
            // a race condition if the last subscriber unsubscribes
            // immediately after the null check and before the event is raised.
            EventHandler<ShapeEventArgs> handler = ShapeChanged;
            if (handler != null)
            {
                handler(this, e);
            }
        }

来源:msdn

【问题讨论】:

标签: c# events delegates race-condition


【解决方案1】:

是的

空条件成员访问的另一个用途是调用委托 以线程安全的方式使用更少的代码。

...

新方法是线程安全的,因为编译器生成代码 只评估一次 PropertyChanged

MSDN Source

【讨论】:

  • thx 顺便说一句,来自 msdn 的示例也可以在不覆盖虚拟方法的情况下工作。你知道这是为什么吗?
  • @GernotAtStackoverflow 你指的是什么虚拟方法?
  • 受保护的虚拟 void OnShapeChanged(ShapeEventArgs e)
  • sry 我明白了...忘记了
猜你喜欢
  • 1970-01-01
  • 2015-01-30
  • 2010-09-25
  • 2010-09-25
  • 2019-06-12
  • 1970-01-01
  • 2020-01-16
  • 2014-04-02
相关资源
最近更新 更多