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. 百度前端技术学院2015JavaScript基础部分-BOM

    5.1 任务描述 实现以下函数 // 判断是否为IE浏览器,返回-1或者版本号 function isIE() { // your implement } // 设置cookie function s ...

  2. 自定义一个只显示年月的DatePicker(UIDatePicker无法实现年月显示)

    HooDatePicker 介绍(introduction) ==================================================项目需要一个DatePicker,只显 ...

  3. python实现的视频下载工具you-get,支持多个国内外主流视频平台

    RT,you-get 是一个视频离线下载工具, https://github.com/soimort/you-get 另一个同类工具 youtube-dl 也是python 实现,虽然名为 youtu ...

  4. 更新UI界面的四种方法

    一.runOnUiThread(new Runnable()): 二.Handler的sendMessage()系列: 三.Handler的post(): 四.View的post():

  5. Varnish介绍

    “Varnish是一款高性能的开源HTTP加速器,挪威最大的在线报纸 Verdens Gang (http://www.vg.no) 使用3台Varnish代替了原来的12台squid,性能居然比以前 ...

  6. 微信支付curl出错及错误码解决方案

    1. curl错误码6 出现场景 PHP Fatal error: Uncaught exception 'WxPayException' with message 'curl出错,错误码:6' in ...

  7. Linux的任务计划--cron入门

    Linux操作系统定时任务系统 Cron 入门 cron是一个linux下的定时执行工具,可以在无需人工干预的情况下运行作业.由于Cron 是Linux的内置服务,但它不自动起来,可以用以下的方法启动 ...

  8. DotNetBar中TextBoxDropDown效果图

  9. vld使用

    1.下载VLD官方版本 2.安装 3.在vs里面的属性里->c/c++->常规->副含附加目录  C:\Program Files (x86)\Visual Leak Detecto ...

  10. LayaAir引擎——(七)

    LayaAir引擎——人物控制TiledMap地图移动和墙壁检测 所需要的软件: LayaAir IDE 1.0.2版本 TiledMap 所需要的东西: 地图:53 * 32,(48*48) 人物: ...