【发布时间】:2019-11-14 20:38:00
【问题描述】:
您如何解释以下行为:
await Task.Run(() => { }).ContinueWith(async prev =>
{
Console.WriteLine("Continue with 1 start");
await Task.Delay(1000);
Console.WriteLine("Continue with 1 end");
}).ContinueWith(prev =>
{
Console.WriteLine("Continue with 2 start");
});
为什么我们会在“Continue with 1 end”之前得到“Continue with 2 start”?
【问题讨论】:
-
ContinueWith 不适用于
async/await,也不了解它们。await是ContinueWith的替换。 -
你为什么用
ContinueWith而不是await? -
因为您不会等待第一次继续。因此,您的第一个延续开始,打印“Continue with 1 start”,调用 Task.Delay,将剩余代码(打印“Continue with 1 end”)安排为另一个隐式延续,返回,开始延续 2。您的隐式延续是然后在 Task.Delay 结束 = 一秒后触发。
-
因为您创建了一个任何东西都不会等待的
async void方法
标签: c# asynchronous async-await