default event add/remove implementation

2019-02-26 10:27发布

问题:

I'm looking to implement some extra logic when event handlers are added or removed to an event.

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?

回答1:

See this series of blog posts.

In C# <4, it used simple delegate operations in locks.

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.



回答2:

Not sure if it's exactly what you are looking for, but this article shows some of the .NET internals of add remove handlers. (Also shows how to get and manipulate those handlers)

http://www.codeproject.com/Articles/308536/How-to-copy-event-handlers-from-one-control-to-ano

If you are trying to add some logic there, you may find the article interesting....