9.3. Handling Exceptions Individually for Each Delegate in a Multicast Delegate
Problem
You have added multiple delegates to a single multicast delegate. Each of these individual delegates must be invoked, regardless of whether an unhandled exception is thrown within one of the delegates. But once a delegate in a multicast delegate throws an unhandled exception, no more delegates are invoked. You need a way to trap unhandled exceptions within each individual delegate while still allowing the rest of the delegates to fire.
Solution
Use the GetInvocationList
method as shown in Recipe 9.1. This method returns each individual delegate from a multicast delegate and, by doing so, allows you to invoke each delegate within the try
block of an exception handler.
The following delegate defines the MyDelegateOperation
delegate type:
public delegate int MyDelegateOperation();
The method shown in Example 9-1 creates a multicast delegate called allInstances
and then uses GetInvocationList
to retrieve each delegate individually. Each delegate is then invoked within the try
block of an exception handler.
Example 9-1. Handling exceptions individually for each delegate in a multicast delegate
public static void TestIndividualInvokesExceptions() { Func<int> myDelegateInstance1 = TestInvokeIntReturn.Method1; Func<int> myDelegateInstance2 = TestInvokeIntReturn.Method2; Func<int> myDelegateInstance3 = TestInvokeIntReturn.Method3; Func<int> allInstances = myDelegateInstance1 + myDelegateInstance2 + 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.