C#异步编程
2021-06-04 20:03
标签:static code write time amp ret image OLE rgs 运行结果: async & await 运行结果: 方法内等待语句须添加await C#异步编程 标签:static code write time amp ret image OLE rgs 原文地址:https://www.cnblogs.com/huangtaiyi/p/10838426.html 1 static void Main(string[] args)
2 {
3 Console.WriteLine("方法开始:"+DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss"));
4 var strRes = Task.Run(() => {return ReturnStr(); });
5 Console.WriteLine("方法结束:"+DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss"));
6 for (int i = 0; i 5; i++)
7 {
8 Console.WriteLine(i);
9 }
10 Console.WriteLine("得到结果后:"+DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss"));
11 Console.WriteLine(strRes.Result);
12 Console.ReadKey();
13 }
14 public static string ReturnStr()
15 {
16 Thread.Sleep(2000);
17 return "方法执行后:"+ DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss");
18 }
1 static void Main(string[] args)
2 {
3 Console.WriteLine("方法开始:" + DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss"));
4 ReturnStr();
5 for (int i = 0; i 5; i++)
6 {
7 Console.WriteLine(i);
8 }
9 Console.WriteLine("方法结束:"+DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss"));
10 Console.ReadKey();
11 }
12
13 public static async Task ReturnStr()
14 {
15 Console.WriteLine("方法执行开始:" + DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss"));
16 Thread.Sleep(2000);
17 var result=await Task.Run(()=>"方法执行后:"+ DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss"));
18 Console.WriteLine(result);
19 }