首先,async 和 await 表明异步执行和等待。异步
async是一个标记,告诉编译器,我可能是一个异步方法。async
await 表明等待,告诉编译器,这里等我返回结果。spa
下面,咱们简单说一下。pwa
static void Main(string[] args) { Stopwatch sw = new Stopwatch(); sw.Start(); MyTest(); Thread.Sleep(5000); Console.WriteLine("Completed"); sw.Stop(); Console.WriteLine(sw.Elapsed.Seconds); Console.ReadKey(); } public static void MyTest() { Test1(); } public static void Test1() { Thread.Sleep(5000); Console.WriteLine("Test1"); }
查看结果:线程
结论:3d
因为Main()和MyTest()都存在 Thread.Sleep(5000),因此总共耗时10秒。code
static void Main(string[] args) { Stopwatch sw = new Stopwatch(); sw.Start(); MyTest(); Thread.Sleep(5000); Console.WriteLine("Completed"); sw.Stop(); Console.WriteLine("耗时:"+sw.Elapsed.Seconds); Console.ReadKey(); } public static async void MyTest() { await Test1(); } public async static Task Test1() { await Task.Delay(5000); Console.WriteLine("Test1"); }
查看结果:blog
结论:编译器
运气不错,运行了2次。string
由于Task异步处理,因此出现了不太同样的结果。
经过咱们这个看出来主线程在5秒就结束了,而线程也在5秒左右结束了。
static void Main(string[] args) { Stopwatch sw = new Stopwatch(); sw.Start(); MyTest(); Thread.Sleep(3000); Console.WriteLine("Completed"); sw.Stop(); Console.WriteLine("耗时:"+sw.Elapsed.Seconds); Console.ReadKey(); } public static async void MyTest() { var q = Test1(); Console.WriteLine("=============="); var q1 = Test2(); Console.WriteLine(await q); Console.WriteLine(await q1); } public static async Task<string> Test1() { await Task.Delay(5000); return "12333"; } public static async Task<string> Test2() { await Task.Delay(3000); return "hello"; }
查看结果:
结论:
主程序运行
1 找到MyTest的"==========",输出了,
2 这个时候因为MyTest中q和q1在等待返回,
主程序继续执行下去,输出了"Completed"
3 这里很好理解,输出"耗时:3"
4 为何把他们都设置为步骤4???由于await阻塞了主程序,在等待返回。
但是!虽然Test1耗时5秒,而Test2耗时3秒。但Test2仍是要等待Test1完成才能输出,由于主程序由于await阻塞了
(若是你把Test1改为1秒,效果就明显了。)