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 multicast delegate is invoked, each delegate within it is invoked in turn. You need to exert more control over such things as the order in which each delegate is invoked, 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, iterate over this array using a for (if enumerating in a nonstandard order) or foreach (for enumerating in a standard order) loop. You can then invoke each Delegate object in the array individually and, optionally, retrieve its return value.

In C#, all delegate types support multicast—that is, any delegate instance can invoke multiple methods each time the instance is invoked if it has been set up to do so. In this recipe, we use the term multicast to describe a delegate that has been set up to invoke multiple methods.

The following method creates a multicast delegate called allInstances and then uses GetInvocationList to allow each delegate to be invoked individually, in reverse order. The Func<int> generic delegate is used to create delegate instances that return an int:

 public static void InvokeInReverse() { Func<int> myDelegateInstance1 = TestInvokeIntReturn.Method1; Func<int> myDelegateInstance2 = TestInvokeIntReturn.Method2; Func<int> myDelegateInstance3 ...

Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.