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 { 10 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