1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace AsyncDemo 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 Console.WriteLine("异步方法测试开始!");//标记时间戳开始 14 AsyncMethod(0);//调用异步方法 15 Console.WriteLine("异步方法结束");//标记时间戳结束 16 Console.ReadKey(); 17 } 18 19 //异步操作 20 private static async void AsyncMethod(int input) 21 { 22 Console.WriteLine("进入异步操作!"); 23 var result = await AsyncWork(input); 24 Console.WriteLine("最终结果{0}", result); 25 Console.WriteLine("退出异步操作"); 26 } 27 28 private static async Task<int> AsyncWork(int val) 29 { 30 for (int i = 0; i < 5; i++) 31 { 32 Console.WriteLine("耗时操作{0}", i); 33 await Task.Delay(1000); 34 val++; 35 } 36 return val; 37 } 38 } 39 }
输出: