我像这样测试了控制台应用程序:
class Program
{
static void Main(string[] args)
{
Test();
Console.WriteLine("C");
Console.ReadLine();
}
static async void Test()
{
Console.WriteLine("A");
await Task.Delay(2000);
Console.WriteLine("B");
}
}
这个应用程序在立即输出 A 和 C 后 2 秒钟才输出 B,看起来很正常。但我读到一篇有关 async/await 的文章 "There Is No Thread" (http://blog.stephencleary.com/2013/11/there-is-no-thread.html), 文章中说 async/await 不会创建额外的线程。
因此回到我的控制台应用程序,我认为主线程被 Console.ReadLine() 阻塞了,所以 Test() 中的其余代码 (Console.WriteLine("B")) 在 Console.ReadLine() 完成之前不会执行。但实际结果不同,无论主线程是否阻塞,其余代码都将执行。
我想知道 await 是否像 CPU 中断一样工作,使指令指针移动到剩余代码(Console.WriteLine("B");),然后在执行后返回中断位置(Console.ReadLine();)?