运行 多个并行任务,如果有任务则取消休息 returns false .NET

Run multiple tasks in parallel and cancel rest if any of them returns false .NET

目前我有这样的代码:

 bool task1Result = await RunTask1(data);
 if(!task1Result)
     return false;

 bool task2Result = await RunTask2(data);
 if(!task2Result)
     return false;

 bool task3Result = await RunTask3(data);
 if(!task3Result)
     return false;

 bool task4Result = await RunTask4(data);
 if(!task4Result)
     return false;

添加示例:

private async Task<bool> RunListOfTasks() {
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken ct = cts.Token;

var tasks = new List<Task<bool>> { RunTask1(data, ct), RunTask2(data, ct), RunTask3(data, ct), RunTask4(data, ct) };
while (tasks.Any())
{
    var currentTask = await Task.WhenAny(tasks);
    if (!await currentTask)
    {
        ct.Cancel();
        return false;
    }
    tasks.Remove(currentTask);
}
return true;
}

是否可以并行 运行 所有这些,如果其中一个失败(例如结果为假),则停止处理其余部分并 return。谢谢

Task.WhenAny-in-a-loop是 an antipattern, because of its 。首选方法是将您的任务包装在另一组任务中,这将包括在结果为 false 时取消 CancellationTokenSource 的功能。然后 await 包装器任务而不是初始任务,并传播它们的结果。

包装任务的一种简单方法是 Select LINQ 运算符:

private async Task<bool> RunListOfTasks()
{
    using CancellationTokenSource cts = new();

    List<Task<bool>> tasks = new()
    {
        RunTask1(data, cts.Token),
        RunTask2(data, cts.Token),
        RunTask3(data, cts.Token),
        RunTask4(data, cts.Token),
    };

    Task<bool>[] enhancedTasks = tasks.Select(async task =>
    {
        try
        {
            bool result = await task.ConfigureAwait(false);
            if (!result) cts.Cancel();
            return result;
        }
        catch (OperationCanceledException) when (cts.IsCancellationRequested)
        {
            return false;
        }
    }).ToArray();

    bool[] results = await Task.WhenAll(enhancedTasks).ConfigureAwait(false);
    return results.All(x => x);
}