首页 > 代码库 > Async异步编程入门示例

Async异步编程入门示例

 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 Program10     {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 }

 输出: