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.

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

  1. Async/Await - Best Practices in Asynchronous Programming z

    These days there’s a wealth of information about the new async and await support in the Microsoft .N ...

  2. [译]Async/Await - Best Practices in Asynchronous Programming

    原文 避免async void async void异步方法只有一个目的:使得event handler异步可行,也就是说async void只能用于event handler. async void ...

  3. Best Practices in Asynchronous Programming

    http://blog.stephencleary.com/ http://blogs.msdn.com/b/pfxteam/

  4. 将 async/await 异步代码转换为安全的不会死锁的同步代码

    在 async/await 异步模型(即 TAP Task-based Asynchronous Pattern)出现以前,有大量的同步代码存在于代码库中,以至于这些代码全部迁移到 async/awa ...

  5. Async/Await FAQ

    From time to time, I receive questions from developers which highlight either a need for more inform ...

  6. 异步模式:Callbacks, Promises & Async/Await

    [译]异步JavaScript的演变史:从回调到Promises再到Async/Await https://www.i-programmer.info/programming/theory/8864- ...

  7. 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 ...

  8. Asynchronous programming with async and await (C#)

    Asynchronous Programming with async and await (C#) | Microsoft Docs https://docs.microsoft.com/en-us ...

  9. .NET 基于任务的异步模式(Task-based Asynchronous Pattern,TAP) async await

    本文内容 概述 编写异步方法 异步程序中的控制流 API 异步方法 线程 异步和等待 返回类型和参数 参考资料 下载 Demo 下载 Demo TPL 与 APM 和 EAP 结合(APM 和 EAP ...

随机推荐

  1. POJ 题目3661 Running(区间DP)

    Running Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 5652   Accepted: 2128 Descripti ...

  2. 适合PHP学习者的学习路线 10个PHP优化技巧

    适合PHP学习者的学习路线: (1) 熟悉HTML/CSS/JS..网页基本元素,完成阶段可自行制作简单的网页,对元素属性相对熟悉 (2) 理解动态语言的概念和运做机制,熟悉基本的PHP语法 (3) ...

  3. SQL高级查询——50句查询(含答案) ---参考别人的,感觉很好就记录下来留着自己看。

    --一个题目涉及到的50个Sql语句 --(下面表的结构以给出,自己在数据库中建立表.并且添加相应的数据,数据要全面些. 其中Student表中,SId为学生的ID) ---------------- ...

  4. GitHub 上一份很受欢迎的前端代码优化指南

    http://segmentfault.com/a/1190000002587334?utm_source=weekly&utm_medium=email&utm_campaign=e ...

  5. Session Tracking Approaches

    cookies url rewriting hidden field see also: http://www.informit.com/articles/article.aspx?p=29817&a ...

  6. 关于jQuery外部框架

    (function(window, undefined) {         var jQuery = ...         ...             window.jQuery = wind ...

  7. LaTex表格内单元格内容强制换行

    /newcommand{/tabincell}[2]{/begin{tabular}{@{}#1@{}}#2/end{tabular}}%放在导言区 %然后使用&/tabincell{c}{} ...

  8. DotNetBar 第2课,窗口设置 Ribbon Form 样式

    1. 新增 windows 窗体时,选 Ribbon Form 2. 窗体继承 Office2007RibbonForm 3. 设计窗口下面,删除 删除styleManager1  组件 窗口效果如下 ...

  9. python requests 模块初探

    现在经常需要在网页中获取相关内容. 其中无非获取网页返回状态,以及查看网页获取的内容几个方面,那么在这方面来看requests可能比urllib2库更简便一些. 比如:先用方法获取网页 r = req ...

  10. PLSQL碰到pls-00103的错误解决办法

    CREATE OR REPLACE PACKAGE PKG_SHOW_CUST_DETAILS AS PROCEDURE SHOW_CUST_DETAILS( myArg VARCHAR2);END ...