Async/Await - Best Practices in Asynchronous Programming

https://msdn.microsoft.com/en-us/magazine/jj991977.aspx

Figure 1 Summary of Asynchronous Programming Guidelines

Name Description Exceptions
Avoid async void Prefer async Task methods over async void methods Event handlers
Async all the way Don’t mix blocking and async code Console main method
Configure context Use ConfigureAwait(false) when you can Methods that require con­text

Avoid Async Void

You should prefer "async Task" to "async void". Async Task methods enable easier error-handling(propagate up or not), composability (Task.waitAll ...) and testability. The exception to this guideline is asynchronous event handlers, which must return void. This exception includes methods that are logically event handlers even if they’re not literally event handlers (for example, ICommand.Execute implementations).

Async All the Way

"Async all the way” means that you shouldn’t mix synchronous and asynchronous code without carefully considering the consequences. In particular, it’s usually a bad idea to block on async code by calling Task.Wait or Task.Result.  This is an common problem for programmers who try to convert just a small part of their application and wrapping it in a synchronous API so the rest of the application is isolated from the changes. Unfortunately, this can cause deadlocks, in the case of GUI or ASP.NET (not if in a console application). The exception semantic for await and Task.Wait is also different, Exception versus AggregateException. So do not do this except in the Main method for console applications.

Figure 5 The “Async Way” of Doing Things

To Do This … Instead of This … Use This
Retrieve the result of a background task Task.Wait or Task.Result await
Wait for any task to complete Task.WaitAny await Task.WhenAny
Retrieve the results of multiple tasks Task.WaitAll await Task.WhenAll
Wait a period of time Thread.Sleep await Task.Delay

Configure Context

Await require context, see the following code, if you swap the commented-out lines in DelayAsync, it will not deadlock,

public static class DeadlockDemo
{
  private static async Task DelayAsync()
  {
    await Task.Delay(1000);  //await Task.Delay(1000).ConfigureAwait(continueOnCapturedContext: false);
  }   // This method causes a deadlock when called in a GUI or ASP.NET context.  public static void Test()     {     // Start the delay.         var delayTask = DelayAsync();     // Wait for the delay to complete.         delayTask.Wait();     } }

This technique is particularly useful if you need to gradually convert an application from synchronous to asynchronous.

You should not use ConfigureAwait when you have code after the await in the method that needs the context.

时间: 2025-01-13 01:38:19

Async/Await - Best Practices in Asynchronous Programming的相关文章

C#的多线程——使用async和await来完成异步编程(Asynchronous Programming with async and await)

https://msdn.microsoft.com/zh-cn/library/mt674882.aspx 侵删 更新于:2015年6月20日 欲获得最新的Visual Studio 2017 RC文档,参考Visual Studio 2017 RC Documentation. 使用异步编程,你可以避免性能瓶颈和提升总体相应效率.然而,传统的异步方法代码的编写方式比较复杂,导致它很难编写,调试和维护. Visual Studio 2012引入了一个简单的异步编程的方法,依赖.NET Fram

(译)Asynchronous programming and Threading in C# (.NET 4.5)

原文地址:http://www.codeproject.com/Articles/996857/Asynchronous-programming-and-Threading-in-Csharp-N 介绍: Asynchronous programming and threading is very important feature for concurrent or parallel programming. Asynchronous programming may or may not us

13 Asynchronous Programming

dotNet1.0 BeginXXX/EndXXX dotNet2.0 Event-Based Asynchronous Programming Asynchronous Component Pattern XXXCompleted事件/XXXAsync dotNet4.5 Task-Based Asynchronous Programming:TAP 基于dotNet4.0中的Task类型 使用编译器时特性 async和await 异常处理 取消

C# Async, Await and using statements

Async, Await 是基于 .NEt 4.5架构的, 用于处理异步,防止死锁的方法的开始和结束, 提高程序的响应能力.比如: Application area           Supporting APIs that contain async methods Web access                    HttpClient , SyndicationClient Working with files           StorageFile, StreamWrite

ASP.NET WebForm中用async/await实现异步出人意料的简单

1. 在.aspx中添加异步标记 <%@ Page Language="C#" Async="true"%> 2. 在.aspx.cs或者.ascx.cs(用户控件)中添加异步方法 private async Task GetMyPosts() { var posts = await ServiceFactory.BlogPostSevice.GetBlogPostsPagedAsync(); rpPosts.DataSource = posts; rp

[.NET] 利用 async &amp; await 进行异步 IO 操作(整理中...)

利用 async & await 进行异步 IO 操作 可以使用异步函数访问文件.使用异步功能,可以调用异步方法,而不使用回调或拆分您在多个方法或 lambda 表达式中的代码. 若要使同步代码异步,则调用异步方法而不是一个同步方法并添加几个关键字到代码中. 您可能认为添加的以下原因 asynchrony 到文件访问调用: Asynchrony 建议于应用程序的响应能力更强.,因为是一个操作的 UI 线程可以执行其他工作. 如果 UI 线程必须执行需要很长时间的代码(例如,超过 50 毫秒),U

Async/Await 异步编程中的最佳做法

近日来,涌现了许多关于 Microsoft .NET Framework 4.5 中新增了对 async 和 await 支持的信息. 本文旨在作为学习异步编程的“第二步”:我假设您已阅读过有关这一方面的至少一篇介绍性文章. 本文不提供任何新内容,Stack Overflow.MSDN 论坛和 async/await FAQ 这类在线资源提供了同样的建议. 本文只重点介绍一些淹没在文档海洋中的最佳做法. 本文中的最佳做法更大程度上是“指导原则”,而不是实际规则. 其中每个指导原则都有一些例外情况

异步编程中的最佳做法(Async/Await) --转

近日来,涌现了许多关于 Microsoft .NET Framework 4.5 中新增了对 async 和 await 支持的信息. 本文旨在作为学习异步编程的“第二步”:我假设您已阅读过有关这一方面的至少一篇介绍性文章. 本文不提供任何新内容,Stack Overflow.MSDN 论坛和 async/await FAQ 这类在线资源提供了同样的建议. 本文只重点介绍一些淹没在文档海洋中的最佳做法. 本文中的最佳做法更大程度上是“指导原则”,而不是实际规则. 其中每个指导原则都有一些例外情况

[转] Understanding JavaScript’s async await

PS:Promise的用处是异步调用,这个对象使用的时候,call then函数,传一个处理函数进去,处理异步调用后的结果 Promise<Action>这样的对象呢,异步调用后的结果是一个Action,传到处理函数里 async/await的作用是,不需要写then函数了,相当于与自动帮你写,你只需要把异步调用后的结果保存下来就可以了 https://ponyfoo.com/articles/understanding-javascript-async-await http://liubin