#377 – Ensure that All of a Delegate’s Methods Are Called by Using GetInvocationList

When an exception occurs during the invocation of one of the methods a delegate refers to, the delegate does not continue invoking methods in its invocation list.

To ensure that all methods in the delegate’s invocation list are called, even when exceptions occur, you can call GetInvocationList and invoke the methods directly, rather than letting the delegate invoke them.

        private delegate void StringHandlerDelegate(string s);

        static void Main()
        {
            // Add two methods to delegate instance
            StringHandlerDelegate del = Method1;
            del += Method2;

            // Invoke
            foreach (StringHandlerDelegate nextDel in del.GetInvocationList())
            {
                try
                {
                    nextDel.Invoke("Yooper");
                }
                catch (Exception xx)
                {
                    Console.WriteLine(string.Format("Exception in {0}: {1}", nextDel.Method.Name, xx.Message));
                }
            }
        }

        static void Method1(string text)
        {
            Console.WriteLine("Method1, {0}", text);
            throw new Exception("Problem in Method1");
        }

        static void Method2(string name)
        {
            Console.WriteLine("Method2, {0}", name);
        }

When you execute the code, you’ll see that Method2 is called, even though Method1 throws an exception.

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a comment