C# - How to start multiple tasks and wait for them all to finish

What you are likely looking for is the method Task.WaitAll(task1, task2, task3..);. The method allows you to wait for several tasks to finish, even though the tasks execute in parallel.

Below is a full example where I start five tasks that wait a different amount of time (1.000, 3.000, 5.000, 8.000 and 10.000 milliseconds):

public static async Task Test()
{
    Task task1 = StartTask(1000);
    Task task2 = StartTask(3000);
    Task task3 = StartTask(10000);
    Task task4 = StartTask(8000);
    Task task5 = StartTask(5000);

    Task.WaitAll(task1, task2, task3, task4, task5);

    // You will not get here until all tasks are finished (in 10 seconds)
    Console.WriteLine("Done!");
}

private static Task StartTask(int timeToWait)
{
    return Task.Run(async () =>
    {
        Console.WriteLine($"Waiting {timeToWait}");
        await Task.Delay(timeToWait);
        Console.WriteLine($"Done waiting {timeToWait}");
    });
}

The tasks start close to simultaneously and finish what they are doing in parallel with the one taking the shortest time finishing first. This can be seen in the below image where they start rather randomly but finish in order:

c-sharp-wait-for-multiple-tasks

However "Done!" is not printed in the console until all 5 tasks have completed, which means it will be printed after ten seconds.

With a list of tasks

Maybe you do not have several individual tasks but rather a list of tasks. In this scenario you can instead use WhenAll rather than WaitAll:

Task task1 = StartTask(1000);
Task task2 = StartTask(3000);
Task task3 = StartTask(10000);
Task task4 = StartTask(8000);
Task task5 = StartTask(5000);

var list = new List<Task> { task1, task2, task3, task4, task5 };

await Task.WhenAll(list);

Everything else is the same as with WhenAll.

That is all!

I hope you found this helpful! Let me know what you think in the comments down below :)