This post originated from an RSS feed registered with .NET Buzz
by Roy Osherove.
Original Post: The problem with Multi-Cast Delegates
Feed Title: ISerializable
Feed URL: http://www.asp.net/err404.htm?aspxerrorpath=/rosherove/Rss.aspx
Feed Description: Roy Osherove's persistent thoughts
Here’s a very interesting situation you can get yourself into when working with delegates: you have a delegate that returns a result. You use this delegate as part of your calculation. What happens when you have multiple targets on the delegate, each returning a different result? Here’s code that demonstrates this:
Class1 has a calculation delegate that receiv different result? Here’s code that demonstrates this:
Class1 has a calculation es 2 numbers and returns a result. It uses this delegate as part of some simple algorithm. The MyClient class attaches 2 different callbacks to the same delegate of Class1, each returning a different result.
What will be the result when MyClient actually calls the DoDelegateWork() function on Class1?
The answer is that whatever target in the invocation list was invoked last will be used to return the actual result. All the other results are discarded. Pretty crazy. It’s pretty weird that we are actually able to do something like this in the framework, and that there is no simple way to avoid this predicament. (I stress, no simple way. We can just through a few hoops to make sure this does not happen, but there is no built in support construct that will deny this from happening. This effect is caused by the fact that all delegates are actually Multicast Delegates.
(PS: this same code works just as well whether the delegate is declared as an event or not. Events were never meant to be used this way, but hey, it's good to know you can of you really need to in some twisted way!)