
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Controlling When and If a Delegate Fires Within a Multicast Delegate
|
487
If you are not familiar with delegates, events, or anonymous methods, you should
read the MSDN documentation on these topics. There are also good tutorials and
example code showing you how to set up and use them in a basic fashion.
9.1 Controlling When and If a Delegate Fires
Within a Multicast Delegate
Problem
You have combined multiple delegates to create a multicast delegate. When this mul-
ticast delegate is fired, each delegate within it is fired in turn. You need to exert more
control over such things as the order in which each delegate is fired, firing only a
subset of delegates, or firing each delegate based on the success or failure of previous
delegates.
Solution
Use the GetInvocationList method to obtain an array of Delegate objects. Next, iter-
ate over this array using a
for (or foreach if order is irrelevant) loop. You can then
invoke each
Delegate object in the array individually and optionally retrieve its return
value.
In .NET, all delegate types support multicast—that is, any delegate instance can invoke
multiple methods each time it is itself invoked if it has been set up to do so. In this rec-
ipe, we use the term multicast to describe a delegate that has been set up to invoke
multiple methods. The ...