多动作赋值加法运行同步吗?

Does multiple action assignment addition run synchronously?

使用 += 运算符时,操作是 运行 同步 还是 异步

Action actions = () => Console.WriteLine("First Action");

actions += () => Console.WriteLine("Second Action");
actions += () => Console.WriteLine("Third Action");
actions += () => Console.WriteLine("Fourth Action");

actions();

此代码块打印:

First Action
Second Action
Third Action
Fourth Action

此操作将 运行 同步,只需执行此操作:

Action actions = () => Console.WriteLine("First Action");

actions += () => Console.WriteLine("Second Action");
actions += () => {
                    Thread.Sleep(2000);
                    Console.WriteLine("Third Action")
                 };
actions += () => Console.WriteLine("Fourth Action");
actions();

并且你可以检查一个线程等待写最后一个

您的问题的答案很简短:操作 运行 同步。就像事件句柄一样,动作按照分配/订阅的顺序顺序执行。

您可能已经注意到,该块已按顺序打印了所有字符串。如果你这样定义:

Action actions = () => Console.WriteLine("2");
actions += () => Console.WriteLine("3");
actions += () => Console.WriteLine("1");
actions += () => Console.WriteLine("4");

无论发生什么,您总是会看到 2 3 1 4 被打印出来。