如何捕获一组任务的异常

How to Catch Exceptions for an array of Tasks

我想了解在尝试等待任务数组时我应该如何在我的 "try" 块中使用什么。

我希望所有任务都等待,不管其中一个任务是否抛出异常,以便它们都能完成。

我应该使用:

var tasks = new Task<CasApiRouterModelExtendedInfo>[mbis.Length];

for (int i = 0; i < mbis.Length; i++)
{
    tasks[i] = CAS.Service.GetAllRouterInterfacesAsync(mbis[i], false, 2);
}

try
{
    Task.WaitAll(tasks);
}
catch (AggregateException ex)
{
    Trace.TraceError("Some interface discoveries failed: ");
    foreach (var innerEx in ex.InnerExceptions)
    {
        Trace.TraceError(innerEx.Message);
    }
}
foreach (var task in tasks)
{
    if (task.Status == TaskStatus.RanToCompletion && task.Result != null)
    {
        returnResults.Add(task.Result);
    }
}

var tasks = new Task<CasApiRouterModelExtendedInfo>[mbis.Length];

for (int i = 0; i < mbis.Length; i++)
{
    tasks[i] = Task.Run(() => CAS.Service.GetAllRouterInterfacesAsync(mbis[i], true, 2));
}

try
{
    for (int i = 0; i < tasks.Length; i++)
    {
        tasks[i].Wait();
    }
}
catch (AggregateException ex)
{
    Trace.TraceError("Some interface discoveries failed: ");
    foreach (var innerEx in ex.InnerExceptions)
    {
        Trace.TraceError(innerEx.Message);
    }
}

foreach (var task in tasks)
{
    if (task.Status == TaskStatus.RanToCompletion && task.Result != null)
    {
        returnResults.Add(task.Result);
    }
}

此外,只要任务没有抛出异常,"task.Status == TaskStatus.RanToCompletion" return 是否为真(这是执行此检查的好方法)吗?

你有什么理由更喜欢 B 吗?我想不出一个。

B是错误的情况下不正确。

另外,风格很差。你的意图是等待所有任务,所以在代码中这样说。不需要手动循环来掩盖你想要完成的事情。

Also, does that "task.Status == TaskStatus.RanToCompletion" return true as long as the task didn't throw an Exception (is this a good way to do this check)?

这检查是否成功完成。很可能,这就是您想要的。任务最终可能会被取消,但您可能会将其视为错误情况。

task.Result != null

这真的是你想要的吗? task.Result 永远不会被系统设置为空。这只有在 GetAllRouterInterfacesAsync 使结果 null.

时才会发生