内容简介:翻译自:https://stackoverflow.com/questions/25691114/where-does-an-async-task-throw-exception-if-it-is-not-awaited
我有以下示例:(请同时阅读代码中的注释,因为它会更有意义)
public async Task<Task<Result>> MyAsyncMethod()
{
Task<Result> resultTask = await _mySender.PostAsync();
return resultTask;
// in real-life case this returns to a different assembly which I can't change
// but I need to do some exception handling on the Result in here
}
让我们假设_mySender的PostAsync方法如下所示:
public Task<Task<Result>> PostAsync()
{
Task<Result> result = GetSomeTask();
return result;
}
问题是:
因为我没有等待MyAsyncMethod中的实际结果,并且如果PostAsync方法抛出异常,在哪个上下文中会抛出并处理异常?
和
有什么办法可以处理我的程序集中的异常吗?
当我尝试将MyAsyncMethod更改为:时,我感到很惊讶:
public async Task<Task<Result>> MyAsyncMethod()
{
try
{
Task<Result> resultTask = await _mySender.PostAsync();
return resultTask;
}
catch (MyCustomException ex)
{
}
}
如果没有等待实际结果,则在此处捕获异常.碰巧PostAsync的结果已经可用,并且在这个上下文中抛出了异常吗?
是否可以使用ContinueWith来处理当前类中的异常?例如:
public async Task<Task<Result>> MyAsyncMethod()
{
Task<Result> resultTask = await _mySender.PostAsync();
var exceptionHandlingTask = resultTask.ContinueWith(t => { handle(t.Exception)}, TaskContinuationOptions.OnlyOnFaulted);
return resultTask;
}
这可以包含在一个单一的“问题”中,但是好的……
Where does an async Task throw Exception if it is not awaited?
TaskScheduler.UnobservedTaskException事件引发了未观察到的任务异常.此事件“最终”被引发,因为在将异常视为未处理之前,该实际上必须进行垃圾回收.
As I don’t await for the actual Result in the MyAsyncMethod and if PostAsync method throws an exception, in which context is the exception going to be thrown and handled?
任何使用async修饰符并返回Task的方法都会将所有异常放在返回的Task上.
Is there any way I can handle exceptions in my assembly?
是的,您可以替换返回的任务,例如:
async Task<Result> HandleExceptionsAsync(Task<Result> original)
{
try
{
return await original;
}
catch ...
}
public async Task<Task<Result>> MyAsyncMethod()
{
Task<Result> resultTask = await _mySender.PostAsync();
return HandleExceptionsAsync(resultTask);
}
I was surprised that when I tried to change MyAsyncMethod to [synchronously return the inner task] the exception was caught here, even if there’s no await for the actual result.
这实际上意味着您调用的方法不是异步任务,正如您的代码示例所示.它是一个非异步的,任务返回方法,当其中一个方法抛出异常时,它就像任何其他异常一样被处理(即,它直接传递给调用堆栈;它不会放在返回的Task上).
Is it possible to use ContinueWith to handle exceptions in the current class?
是的,但等待更清洁.
翻译自:https://stackoverflow.com/questions/25691114/where-does-an-async-task-throw-exception-if-it-is-not-awaited
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- .NET 中让 Task 支持带超时的异步等待
- .NET 编写一个可以异步等待循环中任何一个部分的 Awaiter
- .NET 中什么样的类是可使用 await 异步等待的?
- 在 WPF/UWP 中实现一个可以用 await 异步等待 UI 交互操作的 Awaiter
- 等待队列源码分析
- 全局事务锁等待分析
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
算法的陷阱
阿里尔•扎拉奇 (Ariel Ezrachi)、莫里斯•E. 斯图克 (Maurice E. Stucke) / 余潇 / 中信出版社 / 2018-5-1 / CNY 69.00
互联网的存在令追求物美价廉的消费者与来自世界各地的商品只有轻点几下鼠标的距离。这诚然是一个伟大的科技进步,但却也是一个发人深思的商业现象。本书中,作者扎拉奇与斯图克将引领我们对由应用程序支持的互联网商务做出更深入的检视。虽然从表面上看来,消费者确是互联网商务兴盛繁荣过程中的获益者,可精妙的算法与数据运算同样也改变了市场竞争的本质,并且这种改变也非总能带来积极意义。 首当其冲地,危机潜伏于计算......一起来看看 《算法的陷阱》 这本书的介绍吧!