首页 > 解决方案 > How to return the not-cancelled tasks from Task.WhenAll execution

问题描述

I have a list of tasks that are cancellable; they have their CancellationTokenSource. Their cancellation is independent of others. I want to return all the not-canceled tasks from 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.

There are questions in the StackOverflow "how to cancel a task inside a task," but this question here is not that.

标签: c#async-awaittask-parallel-librarycancellation-token

解决方案


You can retry the rest of the tasks by looping 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())

推荐阅读