问题描述
令我困惑但从未引起任何问题的东西...推荐的事件调度方式如下:
Something that confuses me, but has never caused any problems... the recommended way to dispatch an event is as follows:
public event EventHandler SomeEvent;
...
{
....
if(SomeEvent!=null)SomeEvent();
}
在多线程环境中,这段代码如何保证另一个线程在检查空值和调用事件之间不会改变SomeEvent
的调用列表?
In a multi-threaded environment, how does this code guarantee that another thread will not alter the invocation list of SomeEvent
between the check for null and the invocation of the event?
推荐答案
在 C# 6.0 中,您可以使用 monadic Null 条件运算符 ?.
以简单且线程安全的方式检查 null 并引发事件方式.
In C# 6.0 you can use monadic Null-conditional operator ?.
to check for null and raise events in easy and thread-safe way.
SomeEvent?.Invoke(this, args);
它是线程安全的,因为它只计算左侧一次,并将其保存在一个临时变量中.您可以部分阅读此处标题为空条件运算符.
It’s thread-safe because it evaluates the left-hand side only once, and keeps it in a temporary variable. You can read more here in part titled Null-conditional operators.
这篇关于在事件调度之前检查空值...线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!