EventHandler: What happens in this code?

this code adds new EventHandler (s) registers for an event named NewMail (the eventargs class is named NewMailEventArgs .

 // A PUBLIC add_xxx method (xxx is the event name) // Allows methods to register interest in the event. public void add_NewMail(EventHandler<NewMailEventArgs> value) { // The loop and the call to CompareExchange is all just a fancy way // of adding a delegate to the event in a thread-safe way. EventHandler<NewMailEventArgs> prevHandler; EventHandler<NewMailEventArgs> newMail = this.NewMail; do { prevHandler = newMail; EventHandler<NewMailEventArgs> newHandler = (EventHandler<NewMailEventArgs>)Delegate.Combine(prevHandler, value); newMail = Interlocked.CompareExchange<EventHandler<NewMailEventArgs>>(ref this.NewMail, newHandler, prevHandler); } while(newMail != prevHandler); } 

(source: CLR via C #, chapter 11 Events) What I do not understand is part of do, first we assign newMail prevHandler, then newMail changes (in CompareExchange) to newHandler? Then we check to see if newMail! = PrevHandler?
I'm really confused. Can someone help me understand what exactly is going on here, especially in the do loop?

+5
c # event-handling events delegates
source share
1 answer

As stated in the commentary, it provides a kind of safe way to deal with events in a multi-threaded environment. This is actually quite complicated, but here's how it works:

  • What does Interlocked.CompareExchange mean: if prevHandler == this.NewMail , then this.NewMail = newHandler

  • The whole operation (compare + influence) is atomic , i.e. done at one time (cannot be stopped in the middle of the operation by another thread).

  • If NewMail not equal to prevHandler , then this means that another thread has already executed the same code fragment and has already modified the event handler . Thus, we will not do anything, and we will again take care and try again, hoping the next time . there is no other thread that the event handler has already registered (next time, ll re-read the event handler, now the operation performed by the other thread will be executed).

See also this useful thread .

+3
source share

All Articles