In most modern C# applications, generous usage of events have become the norm. Gone are the days where we were afraid to use them because of the "black magic" code that they seemed to execute.
Today, perhaps the opposite is true, and they are used too lightly, with disregard for the memory leeches they are (those small, black slimly kind that you're never aware of what damage they're doing until it's too late).
Here's some code to make usage of the leeches a little easier :).
The typical firing of an event from C# code looks something like this:
There are 2 essential problems with this code:
- It's too many lines of code for something so mundane.
- What happens if there are more than 1 listeners listening to the event, and one of them throws an exception? Normal .NET behaviour dictates that the other listeners never get to hear about the event, but what if it's important that all listeners know about the event before application execution is halted?
Solution to problem #1: wrap the logic in an extension method
there - isn't that better? Here's sample of the implementation:
Solution to problem #2: expand on the extension method (now that all the logic is conveniently in one place)
...where the boolean parameter tells the extension method to make sure that all the event listeners get to hear about the event before throwing an exception. The exception that is then thrown, is an EventListenerException, which is just basically a wrapper for all exceptions that occurred on the event listener's event handling code.
sample implementation: (called from the event extension method)
Here's some sample code with unit tests included in case you need to play with the code (NUnit 2.4.7 & VS 2008)
PS: It's Silverlight compatible (of course :) )