首先,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秒,效果就明顯了。)