gpt4 book ai didi

c# - 在 await Task.WhenAll() 中隔离异常

转载 作者:太空宇宙 更新时间:2023-11-03 22:42:52 25 4
gpt4 key购买 nike

执行 Task.WhenAll() 时隔离异常的正确方法是什么。这样当其中一个进程(用户)抛出异常时,其他进程会继续处理。

try
{
var usersToProcess = new List<User>();

var processes = new List<Task>();
foreach (var user in usersToProcess)
{
var process = // Set up here
processes.Add(_processHandler.Process(process));
}

await Task.WhenAll(processes); // await all here
}
catch (Exception ex)
{
throw ex;
}

最佳答案

所有任务将并行运行,因此即使一个任务抛出异常,它也不会阻止其他任务停止执行。查看docs :

You apply the Task.WhenAll method to a collection of tasks. The application of WhenAll returns a single task that isn’t complete until every task in the collection is completed. The tasks appear to run in parallel, but no additional threads are created. The tasks can complete in any order.

关于c# - 在 await Task.WhenAll() 中隔离异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51417122/

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