Sobes.tech
Junior — Middle

How to implement waiting for the completion of all tasks in a set of tasks?

sobes.tech AI

Answer from AI

In C#, to wait for the completion of all tasks in a set, you can use the Task.WhenAll method. It takes an array or collection of tasks and returns a task that completes when all the provided tasks are finished.

Example:

Task[] tasks = new Task[]
{
    Task.Run(() => DoWork(1)),
    Task.Run(() => DoWork(2)),
    Task.Run(() => DoWork(3))
};

await Task.WhenAll(tasks);

void DoWork(int id)
{
    // some work
    Console.WriteLine($"Task {id} completed");
}

If you are not using async/await, you can call Task.WaitAll(tasks), which blocks the current thread until all tasks are completed.

How to implement waiting for the completion of all… - sobes.tech