我经常听到/读到以下建议:

在检查事件是否为空并触发它之前,始终要对事件进行复制。这将消除线程的一个潜在问题,即事件在你检查null和你触发事件的位置之间变成null:

// Copy the event delegate before checking/calling
EventHandler copy = TheEvent;

if (copy != null)
    copy(this, EventArgs.Empty); // Call any handlers on the copied list

更新:我认为从阅读优化,这可能也需要事件成员是volatile,但Jon Skeet在他的回答中说,CLR不会优化掉副本。

但与此同时,为了让这个问题发生,另一个线程必须做这样的事情:

// Better delist from event - don't want our handler called from now on:
otherObject.TheEvent -= OnTheEvent;
// Good, now we can be certain that OnTheEvent will not run...

实际的序列可能是这样的:

// Copy the event delegate before checking/calling
EventHandler copy = TheEvent;

// Better delist from event - don't want our handler called from now on:
otherObject.TheEvent -= OnTheEvent;    
// Good, now we can be certain that OnTheEvent will not run...

if (copy != null)
    copy(this, EventArgs.Empty); // Call any handlers on the copied list

重点是OnTheEvent运行后,作者已经取消订阅,但他们只是取消订阅专门避免这种情况发生。当然,真正需要的是在添加和删除访问器中具有适当同步的自定义事件实现。此外,如果在触发事件时持有锁,则可能存在死锁的问题。

So is this Cargo Cult Programming? It seems that way - a lot of people must be taking this step to protect their code from multiple threads, when in reality it seems to me that events require much more care than this before they can be used as part of a multi-threaded design. Consequently, people who are not taking that additional care might as well ignore this advice - it simply isn't an issue for single-threaded programs, and in fact, given the absence of volatile in most online example code, the advice may be having no effect at all.

(在成员声明中分配空委托{}不是更简单吗,这样你就永远不需要在第一时间检查null ?)

Updated: In case it wasn't clear, I did grasp the intention of the advice - to avoid a null reference exception under all circumstances. My point is that this particular null reference exception can only occur if another thread is delisting from the event, and the only reason for doing that is to ensure that no further calls will be received via that event, which clearly is NOT achieved by this technique. You'd be concealing a race condition - it would be better to reveal it! That null exception helps to detect an abuse of your component. If you want your component to be protected from abuse, you could follow the example of WPF - store the thread ID in your constructor and then throw an exception if another thread tries to interact directly with your component. Or else implement a truly thread-safe component (not an easy task).

所以我认为,仅仅做这种复制/检查的习惯是盲目的编程,会给你的代码增加混乱和噪音。要真正防范其他线程,需要做更多的工作。

针对Eric Lippert博客文章的更新:

因此,关于事件处理程序,我错过了一个主要的事情:“事件处理程序必须健壮,即使在事件被取消订阅后也需要被调用”,显然,因此我们只需要关心事件委托为空的可能性。对事件处理程序的需求在任何地方都有记录吗?

所以:“有其他方法可以解决这个问题;例如,初始化处理程序以拥有一个永远不会删除的空操作。但做空检查是标准模式。”

所以我的问题剩下的一个片段是,为什么显式空检查是“标准模式”?另一种方法,分配空委托,只需要将= delegate{}添加到事件声明中,这就消除了每个引发事件的地方的那些臭仪式。可以很容易地确保实例化空委托的成本很低。还是我还遗漏了什么?

当然,就像Jon Skeet所建议的那样,这只是。net 1。X条没有消失的建议,就像它在2005年应该消失的那样?


更新

从c# 6开始,这个问题的答案是:

SomeEvent?.Invoke(this, e);

当前回答

由于条件的原因,JIT不允许执行您在第一部分中讨论的优化。我知道前段时间有人说这是幽灵,但这是不成立的。(我之前和乔·达菲或万斯·莫里森核实过;我不记得是哪个了。)

如果没有volatile修饰符,所取的本地副本可能会过期,但仅此而已。它不会引起NullReferenceException。

是的,确实存在一个竞争条件——但总是会有。假设我们将代码更改为:

TheEvent(this, EventArgs.Empty);

现在假设该委托的调用列表有1000个条目。列表开头的操作完全有可能在另一个线程取消订阅列表结尾附近的处理程序之前执行。但是,该处理程序仍将被执行,因为它将是一个新的列表。(委托是不可变的。)在我看来,这是不可避免的。

使用空委托当然可以避免无效检查,但不能修复竞争条件。它也不能保证您总是“看到”变量的最新值。

其他回答

在c# 6及以上版本中,可以使用new ?运算符如下:

TheEvent ?。调用(这,EventArgs.Empty);

这里是MSDN文档。

请看这里:http://www.danielfortunov.com/software/%24daniel_fortunovs_adventures_in_software_development/2009/04/23/net_event_invocation_thread_safety 这是正确的解决方案,应该经常使用,而不是所有其他变通方法。

通过使用不做任何事情的匿名方法初始化内部调用列表,可以确保它始终至少有一个成员。因为没有外部方可以引用匿名方法,也没有外部方可以删除该方法,因此委托永远不会为空。” -编程。net组件,第二版,由Juval Löwy

public static event EventHandler<EventArgs> PreInitializedEvent = delegate { };  

public static void OnPreInitializedEvent(EventArgs e)  
{  
    // No check required - event will never be null because  
    // we have subscribed an empty anonymous delegate which  
    // can never be unsubscribed. (But causes some overhead.)  
    PreInitializedEvent(null, e);  
}  

“为什么显式空检查是‘标准模式’?”

我怀疑其原因可能是空检查的性能更好。

如果你总是在创建事件时订阅一个空委托,会有一些开销:

构造空委托的开销。 构建包含它的委托链的成本。 每次引发事件时调用无意义委托的成本。

(请注意,UI控件通常有大量的事件,其中大多数从未订阅过。必须为每个事件创建一个虚拟订阅者,然后调用它,这可能会严重影响性能。)

我做了一些粗略的性能测试,看看subscribe-empty-delegate方法的影响,下面是我的结果:

Executing 50000000 iterations . . .
OnNonThreadSafeEvent took:      432ms
OnClassicNullCheckedEvent took: 490ms
OnPreInitializedEvent took:     614ms <--
Subscribing an empty delegate to each event . . .
Executing 50000000 iterations . . .
OnNonThreadSafeEvent took:      674ms
OnClassicNullCheckedEvent took: 674ms
OnPreInitializedEvent took:     2041ms <--
Subscribing another empty delegate to each event . . .
Executing 50000000 iterations . . .
OnNonThreadSafeEvent took:      2011ms
OnClassicNullCheckedEvent took: 2061ms
OnPreInitializedEvent took:     2246ms <--
Done

请注意,对于零或一个订阅者的情况(通常用于事件丰富的UI控件),使用空委托预初始化的事件明显较慢(超过5000万次迭代…)

要了解更多信息和源代码,请访问这篇关于.NET事件调用线程安全的博客文章,这篇文章是我在提出这个问题的前一天发布的(!)

(我的测试设置可能有缺陷,所以请随意下载源代码并自己检查。任何反馈都非常感谢。)

所以我来的有点晚了。:)

至于使用null而不是null对象模式来表示没有订阅者的事件,请考虑以下场景。您需要调用一个事件,但是构造对象(EventArgs)并非简单,而且在一般情况下,事件没有订阅者。如果您能够优化代码,在进行构造参数和调用事件的处理工作之前检查是否有订阅者,这将对您大有好处。

With this in mind, a solution is to say "well, zero subscribers is represented by null." Then simply perform the null check before performing your expensive operation. I suppose another way of doing this would have been to have a Count property on the Delegate type, so you'd only perform the expensive operation if myDelegate.Count > 0. Using a Count property is a somewhat nice pattern that solves the original problem of allowing optimization, and it also has the nice property of being able to be invoked without causing a NullReferenceException.

但是请记住,由于委托是引用类型,所以它们可以为空。也许根本没有好办法隐藏这一事实,只支持事件的空对象模式,所以替代方案可能迫使开发人员同时检查空订阅者和零订阅者。那将比目前的情况更糟糕。

注:这纯粹是猜测。我不涉及。net语言或CLR。

我从未真正认为这是一个大问题,因为我通常只在可重用组件上的静态方法(等)中防止这种潜在的线程错误,而且我不创建静态事件。

我做错了吗?