Avoid race condition ?. operator

大憨熊 提交于 2020-06-28 05:53:05

问题


Does the ?. operator that can be used to invoke a delegate or event avoid race conditions?

Eg. avoid race-condition manually:

//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);
            }
        }

source: msdn


回答1:


Yes

Another use for the null-condition member access is invoking delegates in a thread-safe way with much less code.

...

The new way is thread-safe because the compiler generates code to evaluate PropertyChanged one time only

MSDN Source



来源:https://stackoverflow.com/questions/43814736/avoid-race-condition-operator

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