原文

避免async void

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

async void方法有不同的错误处理机制。当async Task或者async Task<T>方法里面抛出异常时,异常会被捕捉到,并放在Task对象里面。在async void方法里面没有Task对象,因此发生在async void方法里面的异常会直接raised到SynchronizationContext 中。发生在async void方法里面的异常不会被正常捕捉到。

private async void ThrowExceptionAsync()
{
throw new InvalidOperationException();
} public void AsyncVoidExceptions_CannotBeCaughtByCatch()
{
try
{
ThrowExceptionAsync();
}
catch (Exception)
{
// 不会捕捉到这个异常
throw;
}
}

返回Task或者Task<T>的异步方法,可以使用await, Task.WhenAny, Task.WhenAll观察到异步方法是什么时候结束的。async void方法不容易观察到什么时候完成的。async void方法完成后会通知到他们的SynchronizationContext,但是太麻烦了。

Async void方法不利于测试。

死锁

public static class DeadlockDemo
{
private static async Task DelayAsync()
{
await Task.Delay(1000);
} // 在GUI和ASP.NET下这个方法会导致死锁
public static void Test()
{
// Start the delay.
var delayTask = DelayAsync();
// Wait for the delay to complete.
delayTask.Wait();
}
}

死锁的根本原因是await的处理上下文的方式。默认情况下,当一个未完成的Task处于等待时,会捕捉到当前的上下文用于当Task完成时回到该方法。这个上下文就是SynchronizationContext。GUI 和ASP.NET 应用的SynchronizationContext一次只允许一段代码运行。当await完成,它企图在捕捉到的上下文中执行async方法剩下来的代码。但是这个上下文已经有一个线程在跑了,这个线程就是等待这个async方法运行完的方法(在这里就是Test这个同步方法)。这两个方法相互等待对方完成,因此发生了死锁。

控制台应用不会发生死锁。因为它有一个线程池的SynchronizationContext而不是GUI 和ASP.NET 应用一次只允许一段代码运行的SynchronizationContext

解决这个死锁的最好的方案是让Test这个方法也是异步的。控制台方法不能用这个方案,因为Main方法不能是异步的。如果Main方法是异步的,它会在调用的异步方法前返回。

控制台的Main方法是少有的可以调用异步方法的非异步方法。

class Program
{
static void Main()
{
MainAsync().Wait();
} static async Task MainAsync()
{
try
{
// Asynchronous implementation.
await Task.Delay(1000);
}
catch (Exception ex)
{
// Handle exceptions.
}
}
}

Configure Context

回到上面死锁的问题,当一个未完成的Task处于await的时候,默认会捕捉到上下文,捕捉到的这个上下文用于重回异步方法。context的行为会导致另外一个问题---性能问题。As asynchronous GUI applications grow larger, you might find many small parts of async methods all using the GUI thread as their context. This can cause sluggishness as responsiveness suffers from “thousands of paper cuts.”

减少这个导致的性能问题,可以通过ConfigureAwait来实现。

async Task MyMethodAsync()
{
// 代码在最初的上下文中运行
await Task.Delay(1000); // 代码在最初的上下文中运行
await Task.Delay(1000).ConfigureAwait(continueOnCapturedContext: false); // 代码不在最初的上下文中运行了
// 现在的上下文在线程池
}

除了性能外,ConfigureAwait的另外一个重要的作用是可以避免死锁。

[译]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

    https://msdn.microsoft.com/en-us/magazine/jj991977.aspx Figure 1 Summary of Asynchronous Programming ...

  3. [译]async/await中使用阻塞式代码导致死锁 百万数据排序:优化的选择排序(堆排序)

    [译]async/await中使用阻塞式代码导致死锁 这篇博文主要是讲解在async/await中使用阻塞式代码导致死锁的问题,以及如何避免出现这种死锁.内容主要是从作者Stephen Cleary的 ...

  4. [译]async/await中使用阻塞式代码导致死锁

    原文:[译]async/await中使用阻塞式代码导致死锁 这篇博文主要是讲解在async/await中使用阻塞式代码导致死锁的问题,以及如何避免出现这种死锁.内容主要是从作者Stephen Clea ...

  5. [译]async/await中阻塞死锁

    这篇博文主要是讲解在async/await中使用阻塞式代码导致死锁的问题,以及如何避免出现这种死锁.内容主要是从作者Stephen Cleary的两篇博文中翻译过来. 原文1:Don'tBlock o ...

  6. Best Practices in Asynchronous Programming

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

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

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

  8. Async/Await FAQ

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

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

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

随机推荐

  1. char在C语言一个字节表示的数据范围

    #include <stdio.h> //char类型数据范围 [-128,127] // ......-132 -131 -130 -129 -128 .. 127 128 129 13 ...

  2. The xp_cmdshell proxy account information cannot be retrieved or is invalid. Verify that the '##xp_cmdshell_proxy_account##' credential exists and contains valid information.

    In one of our recent migrations, we got the following error when the client tried to fire xp_cmdshel ...

  3. RuntimeException和Exception区别

    1.java将所有的错误封装为一个对象,其根本父类为Throwable, Throwable有两个子类:Error和Exception. 2.Error是Throwable 的子类,用于指示合理的应用 ...

  4. 设置MYSQL数据库编码为UTF-8

    设置MYSQL数据库编码为UTF-8   1.  编辑MySql的配置文件 MySql的配置文件Windows下一般在系统目录下或者在MySql的安装目录下名字叫my.ini,可以搜索,Linux下一 ...

  5. 爬虫基础(五)-----scrapy框架简介

    ---------------------------------------------------摆脱穷人思维 <五> :拓展自己的视野,适当做一些眼前''无用''的事情,防止进入只关 ...

  6. html中的meta标签是什么?有哪些属性?

    meta标签介绍 meta标签是HTML语言head区域的一个辅助性标签,常用于定义页面的说明,关键字,最后修改的日期和其他的元数据.这些元数据将服务于浏览器,搜索引擎和其他网络服务. meta标签的 ...

  7. Tutorial 02_熟悉常用的HDFS操作

    Shell命令实现: (1)向HDFS 中上传任意文本文件,如果指定的文件在HDFS 中已经存在,则由用户来指定是追加到原有文件末尾还是覆盖原有的文件: (2) 从HDFS 中下载指定文件,如果本地文 ...

  8. mysql 8.0.X 创建新的数据库、用户并授权

    一.创建数据库 mysql> create database jira; Query OK, 0 rows affected (0.09 sec) 二.创建用户 mysql> create ...

  9. golang核心Goroutine和channel

    一.Goroutine 1.介绍 goroutine简介 goroutine是go语言中最为NB的设计,也是其魅力所在,goroutine的本质是协程,是实现并行计算的核心.goroutine使用方式 ...

  10. ubuntu 16.04上 mysql 5.7 安装笔记

    一 安装 ubuntu 采用APT安装方式,可参考: Ubuntu 安装mysql和简单操作 Ubuntu 16.04安装MySQL(5.7.18) A Quick Guide to Using th ...