Search code examples
c#async-awaitcancellation

Waiting for multiple tasks when some might be cancelled


I'm trying to wait for multiple tasks, and I expect that some might be cancelled. I'm using this question as a source of inspiration to have WhenAll handle cancelled tasks accordingly...

However, if none of the tasks ever get cancelled, this in turn throws an exception too!

var source = new CancellationTokenSource();

var task1 = Task.Delay(100, source.Token);
source.Cancel();
var task2 = Task.Delay(300);

await Task.WhenAll(task1, task2).ContinueWith(_ => { }, TaskContinuationOptions.OnlyOnCanceled);

In the example above if the source.Cancel() is NOT executed, then the final await will throw an exception. I could fix that by removing the ContinueWith from the final line, but then if a task IS cancelled, the WhenAll will fail with the same error.

What's the correct course of action to wait for a list of tasks when some of them might (but don't have to) be cancelled?


Solution

  • I think the problem is the TaskContinuationOption you pass. In your example you use OnlyOnCanceled. So it only continues with that if a task was cancelled.

    I'm not sure what the desired behaviour is when a task was cancelled. If you only want to proceed when none of them was cancelled, you could use NotOnCanceled. If you want to proceed in either case, with cancelled tasks or not, then you could for example use NotOnFaulted, since cancellation is not regarded as fault.