O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

7.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 fire, 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 fired. 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 7.1. This method returns each individual delegate from a multicast delegate, and by doing so, allows us to invoke each delegate within an exception handler. The following method creates a multicast delegate called All and then uses GetInvocationList to retrieve each delegate individually. Each delegate is then fired within an exception handler:

using System; using System.Security; public class DelegateUtilities { public void TestIndividualInvokesExceptions( ) { MultiInvoke MI1 = new MultiInvoke(TestInvoke.Method1); MultiInvoke MI2 = new MultiInvoke(TestInvoke.Method2); MultiInvoke MI3 = new MultiInvoke(TestInvoke.Method3); MultiInvoke All = MI1 + MI2 + MI3; int retVal = -1; Console.WriteLine("Invoke individually (handle exceptions):"); foreach (MultiInvoke individualMI in All.GetInvocationList( )) { try { retVal = individualMI( ); Console.WriteLine("\tOutput: " + retVal); } catch (SecurityException se) { // ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required