C# 非同步Async與Await示例
阿新 • • 發佈:2020-07-08
1 static void Main(string[] args) 2 { 3 callMethod();//方法中 Method1()是在非同步中執行,與Method2()之間不相互依賴,Method3()依賴於Method1() 4 Console.WriteLine("MainEnd"); 5 Console.ReadKey(); 6 } 7 8 public static async void callMethod() 9 {View Code10 Task<int> task = Method1();//函式中的sleep模擬非同步函式中耗時操作 11 Method2(); 12 Console.WriteLine("M2End"); 13 Method2_1();//函式中的sleep模擬main函式中的耗時操作 14 Console.WriteLine("M2_1End"); 15 int count = await task; 16 Method3(count);17 } 18 19 public static async Task<int> Method1() 20 { 21 int count = 0; 22 await Task.Run(() => 23 { 24 for (int i = 0; i < 20; i++) 25 { 26 Console.WriteLine($" Method 1-{i}");27 Thread.Sleep(100); 28 count += 1; 29 } 30 }); 31 return count; 32 } 33 34 public static void Method2() 35 { 36 Console.WriteLine($" Method 2"); 37 } 38 39 public static void Method2_1() 40 { 41 for (int i = 0; i < 25; i++) 42 { 43 Console.WriteLine($" Method 2-{i}"); 44 Thread.Sleep(60); 45 } 46 } 47 48 public static void Method3(int count) 49 { 50 Console.WriteLine("Total count is " + count); 51 }
執行結果:
可以看出:方法1在Task中執行,方法2、方法2-1在主程式碼裡執行,且互不干擾(實現了非同步執行) 方法3在await task; 之後,在Task執行完畢之後再執行方法3