简体   繁体   中英

How does C# eventhandler work internally?

I guess C# eventhandler has a list of listeners and it loops thru the list when sending a message. My question is how does this works in internally. Does it make a copy of the list before looping it thru and if so, what happens if someone unregister itself after the list has been copied but it has not yet received the message.

Will it still get the message even do it has unregister itself?

A delegate is immutable, so when you are invoking a delegate the list of subscribers is known and fixed. Subscribing or unsubscribing replaces the delegate that underpins the event.

This does indeed mean that in a multi-threaded scenario you can receive an event after unsubscribing, because either:

  1. the delegate was already in the process of being invoked
  2. a snapshot of the delegate had already been obtained for the purpose of invoking

by 2, I mean the usual pattern (to prevent a null-ref during invoke):

var handler = SomeEvent;
// <===== another thread could unsubscribe at this point
if(handler != null) handler(sender, args); // <== or part way through this invoke
// (and it either case, have the event trigger even though they think they have
// unsubscribed)

For that reason, if you are coding complex multi-threaded code with events, you should code defensively such that the event firing after you think you have unsubscribed is not a problem.

These nuances do not really impact single-threaded code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM