我想等待扔AggregateException,不只是第一个异常 [英] I want await to throw AggregateException, not just the first Exception

查看:160
本文介绍了我想等待扔AggregateException,不只是第一个异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在等待出现故障的任务(一个有例外集),伺机将重新抛出异常存储。如果存储的异常是 AggregateException 将重新抛出的第一个并丢弃其余部分。

When awaiting a faulted task (one that has an exception set), await will rethrow the stored exception. If the stored exception is an AggregateException it will rethrow the first and discard the rest.

如何使用等待,并在同一时间抛出原来的 AggregateException ,这样我们就不会意外丢失错误信息?

How can we use await and at the same time throw the original AggregateException so that we do not accidentally lose error information?

请注意,这当然可以认为这哈克解决方案的(围绕等待,然后调用任务如的try-catch。等待)。我真的希望找到一个干净的解决方案。 这里有什么最佳实践?

Note, that it is of course possible to think of hacky solutions for this (e.g. try-catch around the await, then call Task.Wait). I really wish to find a clean solution. What is the best-practice here?

我想用一个自定义的awaiter但内置的 TaskAwaiter 含有大量的魔法,我不知道如何完全再现。它呼吁TPL类型的内部API。我也没有的需要的重现了这一切。

I thought of using a custom awaiter but the built-in TaskAwaiter contains lots of magic that I'm not sure how to fully reproduce. It calls internal APIs on TPL types. I also do not want to reproduce all of that.

下面是一个简短的摄制,如果你想用它玩:

Here is a short repro if you want to play with it:

static void Main()
{
    Run().Wait();
}

static async Task Run()
{
    Task[] tasks = new[] { CreateTask("ex1"), CreateTask("ex2") };
    await Task.WhenAll(tasks);
}

static Task CreateTask(string message)
{
    return Task.Factory.StartNew(() => { throw new Exception(message); });
}

只有两个例外之一运行

请注意,这对堆栈溢出的其他问题不解决这个特定的问题。提示重复时,请小心。

Note, that other questions on Stack Overflow do not address this specific problem. Please be careful when suggesting duplicates.

推荐答案

我在你的问题的标题,的含义不同意等待的行为是不需要的。这使得在绝大多数场景感。在 WhenAll 的情况下,你多久的真正的需要知道的所有的的错误的详细信息,而不是仅仅一个?

I disagree with the implication in your question title that await's behavior is undesired. It makes sense in the vast majority of scenarios. In a WhenAll situation, how often do you really need to know all of the error details, as opposed to just one?

用的主要困难 AggregateException 是异常处理,即,你失去抓特定类型的能力。

The main difficulty with AggregateException is the exception handling, i.e., you lose the ability to catch a particular type.

这就是说,它很容易得到与扩展方法你想要的行为:

That said, it's easy to get the behavior you want with an extension method:

public static async Task WithAggregateException(this Task source)
{
    try
    {
        await source.ConfigureAwait(false);
    }
    catch
    {
        throw source.Exception;
    }
}

这篇关于我想等待扔AggregateException,不只是第一个异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆