c#中多播委托的执行顺序

Pra*_*uka 3 c# delegates

我看了

如果您正在使用多播委托,您应该知道将被调用链接到同一委托的方法的顺序是正式未定义的.因此,您应该避免编写依赖于以任何特定顺序调用此类方法的代码.

但是当我尝试使用这段代码时

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");

                }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的输出

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
Run Code Online (Sandbox Code Playgroud)

显然,委托是按照我编写的指定顺序执行的,并且Three()One()抛出异常的方法之前没有任何方法执行.

所以我缺少一些东西或者委托中的实际方法按指定的顺序执行,我从书中读到的东西意味着什么.

cod*_*eim 6

undefined - 行为被指定为任意的(就像你忘记妻子的生日后会发生什么......)所以取决于任意行为是有潜在危险的.

可能是5年后,微软发布了.NET 7,你的程序结果发生了变化.这是"未定义"的意思,今天没有多少测量值可以让您对下一个版本,甚至您的计算机和Fred的计算机之间感到舒适.所以观察它只是有趣的,但对可靠性没有用.依靠你观察到的东西在技术上是错误的.

有时,供应商会特别记录未定义的内容,以便在实施过程中保持灵活性.

  • 有权威消息来源吗?我刚刚偶然发现了[文档](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/delegates#delegate-inspiration),看来顺序现在已经定义了。 (2认同)
  • @TheConstructor - 完全有可能,因为我的回答,.NET CLR 改变以保证执行顺序。已经 4-5 年了,所以这可能是 .NET 4.5.1 左右。实际上,5 年前我在回答中说“可能是 5 年后,Microsoft 发布 .NET 7 并且您的程序的结果会发生变化”,这非常有趣和讽刺。 (2认同)