原文:为什么不要使用 Async Void ?

问题

在使用 Abp 框架的后台作业时,当后台作业抛出异常,会导致整个程序崩溃。在 Abp 框架的底层执行后台作业的时候,有 try/catch 语句块用来捕获后台任务执行时的异常,但是在这里没有生效。

原始代码如下:

public class TestAppService : ITestAppService
{
private readonly IBackgroundJobManager _backgroundJobManager; public TestAppService(IBackgroundJobManager backgroundJobManager)
{
_backgroundJobManager = backgroundJobManager;
} public Task GetInvalidOperationException()
{
throw new InvalidOperationException("模拟无效操作异常。");
} public async Task<string> EnqueueJob()
{
await _backgroundJobManager.EnqueueAsync<BG, string>("测试文本。"); return "执行完成。";
}
} public class BG : BackgroundJob<string>, ITransientDependency
{
private readonly TestAppService _testAppService; public BG(TestAppService testAppService)
{
_testAppService = testAppService;
} public override async void Execute(string args)
{
await _testAppService.GetInvalidOperationException();
}
}

调用接口时的效果:

原因

出现这种情况是因为任何异步方法返回 void 时,抛出的异常都会在 async void 方法启动时,处于激活状态的同步上下文 (SynchronizationContext) 触发,我们的所有 Task 都是放在线程池执行的。

所以在上述样例当中,此时 AsyncVoidMethodBuilder.Create() 使用的同步上下文为 null ,这个时候 ThreadPool 就不会捕获异常给原有线程处理,而是直接抛出。

线程池在底层使用 AsyncVoidMethodBuilder.Craete() 所拿到的同步上下文,所捕获异常的代码如下:

internal static void ThrowAsync(Exception exception, SynchronizationContext targetContext)
{
var edi = ExceptionDispatchInfo.Capture(exception); // 同步上下文是空的,则不会做处理。
if (targetContext != null)
{
try
{
targetContext.Post(state => ((ExceptionDispatchInfo)state).Throw(), edi);
return;
}
catch (Exception postException)
{
edi = ExceptionDispatchInfo.Capture(new AggregateException(exception, postException));
}
}
}

虽然你可以通过挂载 AppDoamin.Current.UnhandledException 来监听异常,不过你是没办法从异常状态恢复的。

参考文章:

Stephen Cleary: https://msdn.microsoft.com/en-us/magazine/jj991977.aspx

Jerome Laban's:https://jaylee.org/archive/2012/07/08/c-sharp-async-tips-and-tricks-part-2-async-void.html

布鲁克石:https://www.cnblogs.com/brookshi/p/5240510.html

解决

可以使用 AsyncBackgroundJob<TArgs> 替换掉之前的 BackgroundJob<TArgs> ,只需要实现它的 Task ExecuteAsync(TArgs args) 方法即可。

public class BGAsync : AsyncBackgroundJob<string>,ITransientDependency
{
private readonly TestAppService _testAppService; public BGAsync(TestAppService testAppService)
{
_testAppService = testAppService;
} protected override async Task ExecuteAsync(string args)
{
await _testAppService.GetInvalidOperationException();
}
}

为什么不要使用 Async Void ?的更多相关文章

  1. 为什么不要使用 async void?

    问题 在使用 Abp 框架的后台作业时,当后台作业抛出异常,会导致整个程序崩溃.在 Abp 框架的底层执行后台作业的时候,有 try/catch 语句块用来捕获后台任务执行时的异常,但是在这里没有生效 ...

  2. 《C#并发编程经典实例》学习笔记—2.9 处理 async void 方法的异常

    问题 需要处理从 async void 方法传递出来的异常. 解决方案 书中建议尽量不写 async void 这样的方法,如果非写不可,建议在方法内部 try catch 所有的代码,即在方法内部处 ...

  3. 处理async void 方法中无法捕捉异常信息

    利用 NuGet库 Nito.AsyncEx 中的 AsyncContext类. 添加NuGet类库,使用AsyncContext AsyncContext.Run(Action action);

  4. [C#] async 的三大返回类型

    async 的三大返回类型 序 博主简单数了下自己发布过的异步文章,已经断断续续 8 篇了,这次我想以 async 的返回类型为例,单独谈谈. 异步方法具有三个可让开发人员选择的返回类型:Task&l ...

  5. async & await 的前世今生(Updated)

    async 和 await 出现在C# 5.0之后,给并行编程带来了不少的方便,特别是当在MVC中的Action也变成async之后,有点开始什么都是async的味道了.但是这也给我们编程埋下了一些隐 ...

  6. [.NET] 怎样使用 async & await 一步步将同步代码转换为异步编程

    怎样使用 async & await 一步步将同步代码转换为异步编程 [博主]反骨仔 [出处]http://www.cnblogs.com/liqingwen/p/6079707.html  ...

  7. [.NET] 利用 async & await 进行异步 IO 操作

    利用 async & await 进行异步 IO 操作 [博主]反骨仔 [出处]http://www.cnblogs.com/liqingwen/p/6082673.html  序 上次,博主 ...

  8. await and async

    Most people have already heard about the new “async” and “await” functionality coming in Visual Stud ...

  9. C#~异步编程再续~await与async引起的w3wp.exe崩溃-问题友好的解决

    返回目录 关于死锁的原因 理解该死锁的原因在于理解await 处理contexts的方式,默认的,当一个未完成的Task 被await的时候,当前的上下文将在该Task完成的时候重新获得并继续执行剩余 ...

随机推荐

  1. u-boot分析(七)----内存初始化

    u-boot分析(七) 上篇博文我们按照210的启动流程,分析到了时钟初始化,今天我们继续按照u-boot的启动流程对内存的初始化进行分析. 今天我们会用到的文档: 1.        2440芯片手 ...

  2. EF--payload or not

    负载加载非负载加载适用于多对多场境. 一.非负载(payload-free)加载 1.1创建表 create table Album ( AlbumId ,), AlbumName ) ) creat ...

  3. http缓存基本介绍

    https://www.helloweba.com/view-blog-414.html

  4. 原生Js在各大浏览器上、火狐、ie、谷歌、360等出现的不兼容问题。

    1 document.getElementsByName("name")  在Ie低版本,360普通版本,以及火狐低版本不支持. 2 element.innerText 在低版本的 ...

  5. Python基础学习之变量赋值

    1.赋值操作符 Python语言中,等号(=)是主要的赋值操作符: >>> aInt=-100 >>> aString='this is a string' > ...

  6. wget无法建立SSL连接

    在使用wget工具的过程中,当URL使用HTTPS协议时,经常出现如下错误:“无法建立SSL连接”. 这是因为wget在使用HTTPS协议时,默认会去验证网站的证书,而这个证书验证经常会失败.加上&q ...

  7. Gameplay Classes

    每个虚幻游戏类都是一个.h和一个.cpp组成. 类在虚幻中有便准的命名模式. 前缀: A继承于可量产的游戏性类.他们都是Actor,可以直接在游戏中生成. U继承于所有游戏性对象.不能在游戏中直接生成 ...

  8. Oracle 日期加减运算

    -- Start 我们都知道数字可以进行加.减.乘.除等运算.那么,日期可不可以呢?答案是,日期只能进行加.减运算. 在开始操作日期之前,我们先了解一下 Oracle 支持哪些日期数据类型,如下所示: ...

  9. @RequestMapping,@ResponseBody,@RequestBody用法

    本文转载:http://blog.csdn.net/ff906317011/article/details/78552426 1.@RequestMapping 国际惯例先介绍什么是@RequestM ...

  10. dotNetFx40_Client_x86_x64和dotNetFx40_Full_x86_x64这两个有什么区别?两个都要安装还是安装其中一个?

    这个是NET Framework 4.0的安装文件它是支持生成和运行下一代应用程序和 XML Web Services 的内部 Windows 组件,很多基于此架构的程序需要它的支持才能够运行.简单的 ...