this code that adds registers new EventHandler(s) for an event named as 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 don't understand is the do part, first we are assigning newMail to prevHandler, then newMail is changed (in CompareExchange) to newHandler? Then we are checking if newMail != prevHandler?
I am really kinda confused. Can any one help me understand what exactly is going on in here, specially in the do loop?