I am currently writing an ASP.NET server control, which exposes a
number of custom events. I was looking through my code archives
for a helper class, which will safely call handler methods of a
multicast delegate, when an event is triggered. I found the class
I was looking for, and decided to publish it here on my blog for future
reference.
A quick note on multicast delegates - Multicast delegates are delegate
instances that are derived from
System.MulticastDelegate
and can have
more than one instance in their invocation list - essentially they are
delegates
that allow assignment of multiple handler methods. When dealing with
multicast delegates, a question arises about how to deal with
exceptions thrown in handler methods. When the framework executes a
multicast delegate, all handler methods in the invocation list are
executed sequentially. If one of the invoked handler methods
should throw an exception, the remaining handlers in the
list, yet to be executed, are not invoked.
So, let's say that we have a custom event on a control (events are
multicast delegates). The containing code of the control subscribes to
the control's event with two different event handlers. The event
fires, causing the first handler to be invoked, which then happens to
throw an exception. The second event handler will never get
called, which could cause serious malfunction or resource leakage in
the application if the handler had an important part to play. The
helper class, posted below, alleviates this problem by invoking the
handler methods in a delegate invocation list dynamically, whilst
trapping exceptions.
The helper class exposes methods to execute a multicast delegate, both
synchronously and asynchronously. The synchronous method returns
the list of thrown exceptions, whilst calling all handlers in the
invocation list. The asynchronous method ignores any exceptions
and calls each handler in the invocation list on a separate thread.