## 使用 await 操作符获取异步任务结果 C# 5.0中引入了新的语言特性,称为**异步函数(asynchronous function)**。它是TPL之上的更高级别的抽象,真正简化了异步编程。 下面代码中 `AsynchronyWithTPL` 和 `AsynchronyWithAwait` 实现的功能是一样的,可以看出使用 `async` 和 `await` 关键字的写法更加简洁而且易懂。 ```csharp /// <summary> /// 使用await操作符获取异步任务结果 /// </summary> /// <param name="args"></param> static void Main(string[] args) { Task t = AsynchronyWithTPL(); t.Wait(); t = AsynchronyWithAwait(); t.Wait(); Console.ReadLine(); } // 标准TPL的写法 static Task AsynchronyWithTPL() { Task<string> t = GetInfoAsync("Task 1"); Task t2 = t.ContinueWith(task => Console.WriteLine(t.Result), TaskContinuationOptions.NotOnFaulted); Task t3 = t.ContinueWith(task => Console.WriteLine(t.Exception.InnerException), TaskContinuationOptions.OnlyOnFaulted); return Task.WhenAny(t2, t3); } // 使用 async await 关键字的写法 static async Task AsynchronyWithAwait() { try { string result = await GetInfoAsync("Task 2"); Console.WriteLine(result); } catch (Exception ex) { Console.WriteLine(ex); } } static async Task<string> GetInfoAsync(string name) { await Task.Delay(TimeSpan.FromSeconds(2)); return $"Task {name} is running on a thread id {Thread.CurrentThread.ManagedThreadId}. " + $"Is thread pool thread: {Thread.CurrentThread.IsThreadPoolThread}"; } ``` 打印结果 ``` Task Task 1 is running on a thread id 4. Is thread pool thread: True Task Task 2 is running on a thread id 5. Is thread pool thread: True ``` Loading... 版权声明:本文为博主「佳佳」的原创文章,遵循 CC 4.0 BY-NC-SA 版权协议,转载请附上原文出处链接及本声明。 原文链接:https://www.liujiajia.me/2017/7/28/csharp-multi-threading-05-csharp6-01-await 提交