如何 return 未取消的任务 Task.WhenAll 执行

How to return the not-cancelled tasks from Task.WhenAll execution

我有一个可以取消的任务列表;他们有自己的 CancellationTokenSource。他们的取消独立于其他人。我想 return 来自 Task.WhenAll 的所有未取消任务。

var tasks = new List<Task<string>>();

/** some code here **/

var done = await Task.WhenAll(tasks); // This throws an OperationCanceledException,
                                      // when at least one task is cancelled.

Whosebug 中有问题“如何在任务中取消任务”,但这里的问题不是那个。

您可以通过循环重试其余任务 Task.WhenAll

var tasks = new List<Task<string>>();

/** some code here **/
var notCanceled = tasks;
do
{
    try
    {
        await Task.WhenAll(notCanceled);
        break;
    }
    catch (OperationCanceledException)
    {
        notCanceled = notCanceled.Where(t => !t.IsCanceled).ToArray();
    }
} while (notCanceled.Any())

一种方法是将 Task.WhenAll 任务存储在 Task 变量中,这样您就可以添加一个 catch 块来专门处理 IsCanceled案例.

var tasks = new List<Task<string>>();

/** some code here **/

Task whenAll = Task.WhenAll(tasks);
Task<string>[] successfullyCompletedTasks;

try
{
    await whenAll;
    successfullyCompletedTasks = tasks.ToArray();
}
catch when (whenAll.IsCanceled)
{
    successfullyCompletedTasks = tasks.Where(t => !t.IsCanceled).ToArray();
}

// Make sure that our assumptions do not contradict the reality
Debug.Assert(successfullyCompletedTasks.All(t => t.IsCompletedSuccessfully));