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. 怎样用SQL语句查询一个数据库中的所有表?

    怎样用SQL语句查询一个数据库中的所有表?  --读取库中的所有表名 select name from sysobjects where xtype='u'--读取指定表的所有列名select nam ...

  2. OC基本数据存储方式

    /** 一,数据存储 常用方式(5种) 1,XML属性列表 -- 保存在Doucuments文件夹 2,偏好设置(NSUserDefault)-- Library/Preference 需要配合wri ...

  3. 《java小应用程序(Applet)和java应用程序(Application)分别编写的简单计算器》

    Application和Java Applet的区别.Java语言是一种半编译半解释的语言.Java的用户程序分为两类:Java Application和Java Applet.这两类程序在组成结构和 ...

  4. think in java学习笔记

    java作用域关键字: public:任何人均可使用 private:除您自己.类型的创建者以及那个类型的内部函数成员,其他任何人都不能访问 protected:只有继承的类可以访问 friendly ...

  5. android layout_weight讲解

    Layout_weight是线性布局,也就是LinearLayout里面用到的,下面通过实验来看这个Layout_weight的特性. 1.当控件的属性android:layout_width=&qu ...

  6. [BZOJ 3223 & Tyvj 1729]文艺平衡树 & [CodeVS 3243]区间翻转

    题目不说了,就是区间翻转 传送门:BZOJ 3223 和 CodeVS 3243 第一道题中是1~n的区间翻转,而第二道题对于每个1~n还有一个附加值 实际上两道题的思路是一样的,第二题把值对应到位置 ...

  7. [GodLove]Wine93 Tarining Round #8

    比赛链接: http://vjudge.net/contest/view.action?cid=47644#overview 比赛来源: 2012 ACM/ICPC Asia Regional Tia ...

  8. logstash 添加nginx日志

    选择需求分类废话少说直接上图 第一张图: 2.此图搭配的日志格式是: log_format main '$remote_addr - $remote_user [$time_local] $http_ ...

  9. iOS 源代码管理工具之SVN

    源代码管理工具之SVN 源代码管理工具SVN是一款非常强大的源代码管理工具,现在国内70%-90%的公司都在使用SVN来管理源代码,下面就让小编给大家着重介绍一下SVN的使用,SVN的使用主要分为下面 ...

  10. Android studio快捷键大全 和 eclipse对照(原)

    Ctrl+空格                  代码提示                           (同Eclipse中Alt+/) Ctrl+Shjft+N             项目 ...