gpt4 book ai didi

c# - 执行所有任务,即使抛出异常

转载 作者:行者123 更新时间:2023-11-30 13:26:24 25 4
gpt4 key购买 nike

我得到了以下方法:

public async Task PublishAsync<TApplicationEvent>(TApplicationEvent e)
where TApplicationEvent : ApplicationEvent
{
using (var scope = _container.CreateScope())
{
var implementations = scope.ResolveAll<IApplicationEventSubscriber<TApplicationEvent>>();
var tasks = implementations.Select(x => x.HandleAsync(e));
try
{
await Task.WhenAll(tasks);
EventPublished(this, new EventPublishedEventArgs(scope, e, true));
}
catch
{
EventPublished(this, new EventPublishedEventArgs(scope, e, false));
throw;
}
}
}

我以为所有任务都会在抛出异常之前执行,但似乎当第一个任务抛出异常时该方法就中止了。

我可以配置 WhenAll 来执行所有任务并在返回之前生成包含所有失败的 AggregateException 吗?

最佳答案

这正是 WhenAll 所做的。但是,当您 await 一个任务抛出一个包含多个异常的聚合异常时,它将仅重新抛出聚合异常中的第一个异常,而不是重新抛出聚合异常本身。 (这是因为绝大多数抛出异常的任务在聚合中永远不会有多个表达式,因此解包异常几乎总是所需的行为。)

await 之前简单地保持对 Task 的引用,以便稍后可以访问聚合异常,或者干脆不要await WhenAll 的结果,而是使用手动延续。

关于c# - 执行所有任务,即使抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24437127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com