例如productUpdate.UpdateAsync(...),当调用异步代码时,它可能会抛出具有多个内部异常或只有一个异常的 AggregateException。这一切都取决于内部如何实现 UpdateAsync。问题:由于await只解开 AggregateException 中异常列表中的第一个异常,下面的特殊代码试图规避它,但这很笨拙,理想情况下,在我调用某个外部库的异步代码的每个地方,可能有一个AggregateException 有多个异常。在所有这些地方都有这个有意义吗?(当然可能可以进入一个辅助方法,但这不是这里的重点)然后还有一个问题是我通过捕获这些异常做了什么有意义的事情。我认为它在所有地方都没有意义。你的想法?var t1 = FooAsync();var t2 = BarAsync();var allTasks = Task.WhenAll(t1, t2);try{ await allTasks;}catch (Exception){ var aggEx = allTasks.Exception as AggregateException; // todo: do something with aggEx.InnerExceptions}更新:在此处为用户Dave添加了完整的重现代码以及运行它的结果:using System;using System.Threading.Tasks;class Example{ static void Main() { BlahAsync().Wait(); } static async Task BlahAsync() { var t1 = FooAsync(throwEx: true); var t2 = BarAsync(throwEx: true); var allTasks = Task.WhenAll(t1, t2); try { await allTasks; } catch (AggregateException agex) { Console.WriteLine("Caught an aggregate exception. Inner exception count: " + agex.InnerExceptions.Count); } } static async Task FooAsync(bool throwEx) { Console.WriteLine("FooAsync: some pre-await code here"); if (throwEx) { throw new InvalidOperationException("Error from FooAsync"); } await Task.Delay(1000); Console.WriteLine("FooAsync: some post-await code here"); } static async Task BarAsync(bool throwEx) { Console.WriteLine("BarAsync: some pre-await code here"); if (throwEx) { throw new InvalidOperationException("Error from BarAsync"); } await Task.Delay(1000); Console.WriteLine("BarAsync: some post-await code here");
1 回答
- 1 回答
- 0 关注
- 176 浏览
添加回答
举报
0/150
提交
取消