Just Code‎ > ‎

C# - Playing with delegate invocation list, Combine, Remove

posted Jan 7, 2013, 5:33 AM by Peter Henell   [ updated Jan 7, 2013, 5:51 AM ]
Producer producer = new Producer();
            Consumer consumer = new Consumer();

            {
                Action a = new Action(producer.Produce);
                Action b = new Action(consumer.Consume);
                Action c = new Action(() =>
                    {
                        Console.WriteLine("Anonymous Method!");
                    });

                var combined = Delegate.Combine(a, b, c);

                combined.DynamicInvoke();
                Delegate.Remove(combined, a).DynamicInvoke();
            }
            Console.WriteLine();
            {
                Action<int> a = new Action<int>(i =>
                {
                    Console.Write("A ");
                    Console.WriteLine(i);
                });
                Action<int> b = new Action<int>(i =>
                {
                    Console.Write("B ");
                    Console.WriteLine(i);
                });
                Action<int> c = new Action<int>( i =>
                {
                    Console.Write("C ");
                    Console.WriteLine(i);
                });

                var combined = Delegate.Combine(a, b, c);
                int counter = 0;
                Console.WriteLine("DynamicInvoce on the delegate");
                combined.DynamicInvoke(counter++);

                Console.WriteLine("Foreach");
                foreach (var item in combined.GetInvocationList())
                {
                    item.DynamicInvoke(counter++);
                }
                
                Console.WriteLine("Delegate remove");
                Delegate.Remove(combined, a).DynamicInvoke(counter--);
                
                // Can use shorthand adding removing as long as they are of the same type
                Console.WriteLine("Shorthand");
                var ny = a + b;
                var another = ny += c += a + b + c ;
                another.DynamicInvoke(10);

            }

Output:
Producing
Consume!
Anonymous Method!
Consume!
Anonymous Method!

DynamicInvoce on the delegate
A 0
B 0
C 0
Foreach
A 1
B 2
C 3
Delegate remove
B 4
C 4
Shorthand
A 10
B 10
C 10
A 10
B 10
C 10
Comments