C#异步中的Task,async,await

时间:2021-09-27 08:20:20

class Program { static void Main(string[] args) { Console.WriteLine("我是主线程,,线程ID:{0}", Thread.CurrentThread.ManagedThreadId); TestAsync(); Console.ReadLine(); } static async void TestAsync() { Console.WriteLine("挪用GetReturnResult()之前,线程ID:{0}。当前时间:{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss")); var name = GetReturnResult(); Console.WriteLine("挪用GetReturnResult()之后,线程ID:{0}。当前时间:{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss")); //异步回调内容 //在await以及之后的代码城市梗阻 Console.WriteLine("得到GetReturnResult()要领的功效:{0}。当前时间:{1}", await name, DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss")); Console.WriteLine("await之后的内容。当前时间:{0}", DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss")); //异步回调内容 } static async Task<string> GetReturnResult() { Console.WriteLine("执行Task.Run之前, 线程ID:{0}", Thread.CurrentThread.ManagedThreadId); return await Task.Run(() => { Thread.Sleep(5000); Console.WriteLine("GetReturnResult()要领里面线程ID: {0}", Thread.CurrentThread.ManagedThreadId); return "我是返回值"; }); } }