为什么不要使用 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
解决
可以使用 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 ?的更多相关文章
- 为什么不要使用 async void?
问题 在使用 Abp 框架的后台作业时,当后台作业抛出异常,会导致整个程序崩溃.在 Abp 框架的底层执行后台作业的时候,有 try/catch 语句块用来捕获后台任务执行时的异常,但是在这里没有生效 ...
- 《C#并发编程经典实例》学习笔记—2.9 处理 async void 方法的异常
问题 需要处理从 async void 方法传递出来的异常. 解决方案 书中建议尽量不写 async void 这样的方法,如果非写不可,建议在方法内部 try catch 所有的代码,即在方法内部处 ...
- 处理async void 方法中无法捕捉异常信息
利用 NuGet库 Nito.AsyncEx 中的 AsyncContext类. 添加NuGet类库,使用AsyncContext AsyncContext.Run(Action action);
- [C#] async 的三大返回类型
async 的三大返回类型 序 博主简单数了下自己发布过的异步文章,已经断断续续 8 篇了,这次我想以 async 的返回类型为例,单独谈谈. 异步方法具有三个可让开发人员选择的返回类型:Task&l ...
- async & await 的前世今生(Updated)
async 和 await 出现在C# 5.0之后,给并行编程带来了不少的方便,特别是当在MVC中的Action也变成async之后,有点开始什么都是async的味道了.但是这也给我们编程埋下了一些隐 ...
- [.NET] 怎样使用 async & await 一步步将同步代码转换为异步编程
怎样使用 async & await 一步步将同步代码转换为异步编程 [博主]反骨仔 [出处]http://www.cnblogs.com/liqingwen/p/6079707.html ...
- [.NET] 利用 async & await 进行异步 IO 操作
利用 async & await 进行异步 IO 操作 [博主]反骨仔 [出处]http://www.cnblogs.com/liqingwen/p/6082673.html 序 上次,博主 ...
- await and async
Most people have already heard about the new “async” and “await” functionality coming in Visual Stud ...
- C#~异步编程再续~await与async引起的w3wp.exe崩溃-问题友好的解决
返回目录 关于死锁的原因 理解该死锁的原因在于理解await 处理contexts的方式,默认的,当一个未完成的Task 被await的时候,当前的上下文将在该Task完成的时候重新获得并继续执行剩余 ...
随机推荐
- SpringCloud的学习记录(2)
这一章节主要讲如何搭建eureka-client项目. 在我们生成的Demo项目上右键点击New->Module->spring Initializr, 然后next, 填写Group和A ...
- java:xml解析
DOM.SAX.JDOM.DOM4J四种解析:https://www.cnblogs.com/longqingyang/p/5577937.html Java解析XML文件例子:https://blo ...
- UI自动化录制工具----UI Recorder
1.系统和工具包 windows 7 64位 jdk,nodejs,webdriver,浏览器都放在工具包目录内.(晚上回去把文件上传到云盘,在分享给大家) 2.安装JDK和node.js 2.1 J ...
- 开源框架 epics,开源画面编辑软件 edm
epics Experimental Physics and Industrial Control System 一套开源软件框架,实验物理和工业控制系统 http://www.aps.anl.gov ...
- MySQL数据库实验二:单表查询
实验二 单表查询 一.实验目的 理解SELECT语句的操作和基本使用方法. 二.实验环境 是MS SQL SERVER 2005的中文客户端. 三.实验示例 1.查询全体学生的姓名.学号.所在系. ...
- Aizu The Maximum Number of Customers
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_5_A The Maximum Number of Customers Ide ...
- 154. Find Minimum in Rotated Sorted Array II(Binary search)
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/description/ -- leetcode follo ...
- react里面引入图片
引入图片确实走了很多的坑,开始的认知里,所有静态页面都需要放在public里面能执行,代码是这样的 css .back{ background-image: url('/images/homeBack ...
- Hive 常用命令和语句
示例数据库为 db_hive 1. 创建表 create-table.sql create table if not exists db_hive.tb_user ( id int, username ...
- 2.初识CronTrigger
开发工具:Eclipse 代码下载链接:https://github.com/theIndoorTrain/QuartzDemo.git 前言: 在1.初始Quartz里面,我们介绍了quartz的一 ...