I read that
If you are using multicast delegates, you should be aware that the order in which methods chained to the same delegate will be called is formally undefined. You should, therefore, avoid writing code that relies on such methods being called in any particular order.
But when I experimented using this code
using System;
namespace Wrox.ProCSharp.Delegates
{
class Program
{
static void One()
{
Console.WriteLine("watch when i occur");
throw new Exception("Error in watching");
}
static void Two()
{
Console.WriteLine("count");
}
static void Three()
{
Console.WriteLine("great");
}
static void Main()
{
Action d1 = Two;
d1+=Two;
d1+=Two;
d1+=Two;
d1+=One;
d1+=Three;
d1+=Three;
d1+=Three;
Delegate[] delegates = d1.GetInvocationList();
foreach (Action d in delegates)
try
{
d1();
}
catch(Exception)
{
Console.WriteLine("Exception Caught");
}
}
}
}
this is the output I got
count
count
count
count
watch when i occur
Exception Caught
count
count
count
count
watch when i occur
Exception Caught
count
count
count
count
watch when i occur
Exception Caught
count
count
count
count
watch when i occur
Exception Caught
count
count
count
count
watch when i occur
Exception Caught
count
count
count
count
watch when i occur
Exception Caught
count
count
count
count
watch when i occur
Exception Caught
count
count
count
count
watch when i occur
Exception Caught
Clearly the delegate is executing in the very specified order I wrote it in, and none of the Three()
methods executes before the One()
method which throws exception.
So is there something I am missing or actually methods in delegates executes in specified order and what I read from the book meant something else.