【发布时间】:2019-11-27 15:31:12
【问题描述】:
考虑以下方法:
public static void Main(string[] args)
{
Stopwatch stopwatch = new Stopwatch();
// Begin timing.
stopwatch.Start();
Task task = dosomething(stopwatch);
Console.WriteLine("Waiting for async to finish {0}", stopwatch.Elapsed);
task.Wait();
Console.WriteLine("After wait {0}",stopwatch.Elapsed);
// Stop timing.
stopwatch.Stop();
// Write result.
}
public static async Task dosomething(Stopwatch stopwatch)
{
Console.WriteLine("Started async", stopwatch.Elapsed);
await dos();
Console.WriteLine("Ended async", stopwatch.Elapsed);
}
public static async Task dos()
{
Thread.Sleep(5000);
Thread.Sleep(1000);
}
}
}
我本来希望输出是这样的:
开始异步
等待异步完成
结束异步
等待之后
但我得到以下输出
开始异步
结束异步
等待异步完成 00:00:06.0990283
等待 00:00:06.0992659
我认为当您等待方法完成时,控制权会返回给调用者。因此,应该在“结束异步”之前调用“等待异步完成”。
【问题讨论】:
-
不要忽略警告。编译器应该已经提醒您
dos没有await任何东西,因此将同步完成。使用await Task.Delay,而不是Thread.Sleep。asyncnot 的意思是“为我在后台运行它”,它的意思是“允许我使用await语法来编写异步代码,就好像它是同步的一样”。您仍然需要提供实际的异步代码。 -
微软有一些写得很好的关于异步编程的文章值得一读。从这里开始:Asynchronous programming with async and await.
-
我在 dotnetfiddle.com 上运行它没有看到任何警告 >.
标签: c# async-await