问题描述
我希望在事件处理程序添加或删除到事件时实现一些额外的逻辑.
I'm looking to implement some extra logic when event handlers are added or removed to an event.
我知道 .net 中的默认实现最近发生了变化.
I'm aware that the default implementation in .net changed recently.
我想让我的实现尽可能接近默认实现.
I'd like to keep my implementation as close to the default implementation as possible.
谁能指出/提供一些东西来展示编译器如何实现事件?
Can anyone point me to/provide something that shows how the compliler implements events?
推荐答案
参见 本系列博文.
在 C# <4 中,它在 lock
s 中使用了简单的委托操作.
In C# <4, it used simple delegate operations in lock
s.
在 C# 4+ 中,它通过在循环中调用 Interlocked.CompareExchange
来使用更高级的无锁算法;在反编译器中查看更多细节.
In C# 4+, it uses a fancier lock-free algorithm by calling Interlocked.CompareExchange
in a loop; look at it in a decompiler for more detail.
如果您确定您的类将永远在多个线程上使用,那么您不需要任何这些;您可以简单地使用非同步委托算法.
If you're sure that your classes will never be used on multiple threads, you don't need any of that; you can simply use unsynchronized delegate arithmetic.
这篇关于默认事件添加/删除实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!