多个操作分配添加是否同步运行?

时间:2017-12-04 15:17:01

标签: c# asynchronous async-await synchronization action

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

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

2 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:0)

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

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

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

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