问题
有多个任务在并行运行,所有任务都可能抛出异常,也可能没有任何一个任务抛出异常。当所有任务完成后,必须报告所有可能发生的异常(通过日志、电子邮件、控制台输出等方式)。
期望行为
我可以使用异步 lambda 在 linq 中构建所有任务,然后使用 Task.WhenAll(tasks)
并行运行它们。然后我可以捕获 AggregateException
并报告每个单独的内部异常。
实际行为
会抛出一个 AggregateException
,但它只包含一个内部异常,无论抛出了多少个单独的异常。
最小完整可验证示例
static void Main(string[] args)
{
try
{
ThrowSeveralExceptionsAsync(5).Wait();
}
catch (AggregateException ex)
{
ex.Handle(innerEx =>
{
Console.WriteLine($"\"{innerEx.Message}\" was thrown");
return true;
});
}
Console.ReadLine();
}
private static async Task ThrowSeveralExceptionsAsync(int nExceptions)
{
var tasks = Enumerable.Range(0, nExceptions)
.Select(async n =>
{
await ThrowAsync(new Exception($"Exception #{n}"));
});
await Task.WhenAll(tasks);
}
private static async Task ThrowAsync(Exception ex)
{
await Task.Run(() => {
Console.WriteLine($"I am going to throw \"{ex.Message}\"");
throw ex;
});
}
输出结果
请注意,“我要扔”消息的输出顺序可能会因竞争条件而改变。
I am going to throw "Exception #0"
I am going to throw "Exception #1"
I am going to throw "Exception #2"
I am going to throw "Exception #3"
I am going to throw "Exception #4"
"Exception #0" was thrown
static async Task Main
。 - Brad Masync Main
内部的工作方式)。 - Camilo Terevinto