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. linux中的内存申请函数的区别 kmalloc, vmalloc

    kmalloc是返回连续内存的内存分配函数 vmalloc是返回较大内存空间的,不需要连续的内存分配函数.其速度较慢,并且不能在中断上下文调用.

  2. Socket支持多用户并发访问的解决办法

    //创建线程池,池中具有(cpu个数*50)条线程 ExecutorService executorService = Executors.newFixedThreadPool(Runtime.get ...

  3. C语言程序设计第十次作业

    一.实验内容        1.有5名学生,每名学生有语文.数学和外语3门课的考试成绩.编程统计各学生的总分和平均分以及所有学生各科的平均分.要求成绩在程序中初始化,结果以表格的形式输出.      ...

  4. php实现函数重载

    java..net等强类型预言中都有方法重载,但是PHP是弱类型语言,不能确定参数的类型, 而且如果php定义的方法接收一个参数,调用的时候传入多个也不会有问题,所以不能进行重载. 但是我们可以通过p ...

  5. JAVAWEB学习总结 SERVLET开发(二)

    一.ServletConfig对象 1.1.配置servlet初始化参数 在servlet的配置文件中web.xml中,可以使用一个或多个<init-param>标签为servlet配置一 ...

  6. 子级与父级的margin合并的问题

    子级加上了margin以后,发现其父级也移动了相应的margin值.外边距合并.换成padding;在父级上加overflow:hidden;

  7. django开发过程中静态文件路径配置

    在demo项目的settings.py文件中找到 STATICFILES_DIRS STATICFILES_DIRS = ( 'static', #这个名字是项目根目录下的文件夹名称,注意后面有逗号 ...

  8. Container With Most Water -- LeetCode 11

    Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai).  ...

  9. Java记事本编译

    配置环境: 在“系统变量”栏下执行三项操作:①新建“Java_Home”,设置其值为 JDK所在的绝对路径,如果你的事刚才的默认路径,那值为:C:\Program Files\Java\jdk1.7. ...

  10. JavaScript:substr vs substring vs slice

    参考文章: JavaScript取子串方法slice,substr,substring对比表