我正在测试异步等待和任务功能,但似乎我漏掉了一些东西。
当我像这样写:A是起点。
void A()
{
Debug.WriteLine("pre B");
B();
Debug.WriteLine("post B");
}
async void B()
{
Debug.WriteLine("pre C");
await C();
Debug.WriteLine("post C")
}
async Task C()
{
await Task.Yield();
Debug.WriteLine("pre D");
await D();
Debug.WriteLine("post D");
}
async Task D()
{
Debug.WriteLine("inside D");
}
我在调试控制台中得到的输出为:
pre B,
pre C,
pre D,
inside D,
post D,
post C,
post B
它是否以异步方式运行?我猜不是,但它应该以什么样的方式运行呢?
pre B,
pre C,
post B,
post C,
pre D,
inside D,
post D
所以问题出在哪里呢?
post B
输出。请自行阅读 B 方法的主体(C 同理)- 写下pre C
,然后等待 C 完成,再写下post C
。从逻辑上讲,只有在 C 完成后才能写入post C
。此时,所有与D
相关的消息必须已经被写入。 - Damien_The_Unbelieverasync
/await
有一些误解,通常通过阅读Eric Lippert的《C# 5.0中的异步编程第二部分:等待何时到来?》可以解决 - 例如,“异步方法的整个重点在于尽可能地保持在当前线程上”。 - Damien_The_Unbeliever