Search code examples
c#taskcancellation

C# - Wait For All Tasks In Array To Complete Or Fail


I have a list of Tasks, the tasks do work on different databases then update a set of results on a central database.

If I can't connect to the central database the desired behaviour is to cancel all the tasks, wait for the running tasks to successfully stop (as it's a cooperative thing) then quit the program.

I've written a few lines of code to test cancelling tasks:

var cancellationTokenSource = new CancellationTokenSource();
var taskList = new List<Task>();
taskList.Add(new Task(() => { Thread.Sleep(5000); }, cancellationTokenSource.Token));
taskList.Add(new Task(() => { Thread.Sleep(5000); }, cancellationTokenSource.Token));
taskList.ForEach(task => task.Start());
cancellationTokenSource.Cancel();
Task.WaitAll(taskList.ToArray());

I know I should normally periodically check the cancellation token within the tasks executing code but for now I'm just testing my understanding of how cancelling works.

When I run it I get the error:

enter image description here

You can pass a cancellation token to WaitAll but thats for actually cancelling the WaitAll

enter image description here

Essentially I just want to wait until all tasks have either run to completion or stopped due to being cancelled so I can safely quit.

I feel like I'm probably missing something simple, if anyone could shed some light on how to accomplish this that would be really appreciated.

Many Thanks


Solution

  • This is a possible duplicate of Task.WaitAll throws OperationCanceledException

    Essentially what you need is

    Task.WhenAll(taskA, taskB, taskC).Wait()
    

    As mentioned in the answer above.