小小一方士 C# Async\Await
生活随笔
收集整理的這篇文章主要介紹了
小小一方士 C# Async\Await
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
思考如下代碼輸出結果:
1 Func<int, Task<int>> function = async x => 2 { 3 Console.WriteLine(x); 4 await Task.Delay(x * 1000); 5 Console.WriteLine($"{x}-qweqwe"); 6 return x * 2; 7 }; 8 Stopwatch st = new Stopwatch(); 9 st.Start(); 10 Task<int> first = function(5); 11 Task<int> second = function(2); 12 13 Console.WriteLine(first.Result); 14 Console.WriteLine(second.Result); 15 st.Stop(); 16 Console.WriteLine(st.ElapsedMilliseconds);輸出結果:
思考.總結:
1.首先從所用時間"5018"確實可以看出異步得作用;
2.async 是基于任務得異步;
3.對于輸出結果,變換一下代碼配合其結果更易于理解;
改變后
輸出結果
4.注意async和await得用法:
? ? ? ? ? ?a.簡單理解為,async修飾時,標識這是一個異步方法,當遇見await時進行阻塞主線程異步執行,在未遇見await,不會進行異步處理;
? ? ? ? ? ?b.async修飾下得方法,必需含有至少一個await,雖然不含await時編譯器仍能通過,但會??
所以i,這點需要注意;
? ? ? ? ? ? c.此段代碼給出了如何編寫底層異步方法(如果想要異步編程,需要從底層開始編寫,這樣后邊使用的時候就是異步)的demo;又如下面代碼:
1 async Task<int> Sum(int a, int b) 2 { 3 Console.WriteLine("di 0"); 4 if (a == 0 && b == 0) 5 { 6 Console.WriteLine("di x"); 7 return 0; 8 } 9 return await Task.Run(async () => 10 { 11 Console.WriteLine("di 1"); 12 await Task.Delay(2000); 13 Console.WriteLine("di 2"); 14 return a + b; 15 }); 16 }?
轉載于:https://www.cnblogs.com/LPudding/p/11095473.html
總結
以上是生活随笔為你收集整理的小小一方士 C# Async\Await的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 前端 vue + element + v
- 下一篇: 父爱如山母爱如海