0
0
C Sharp (C#)programming~5 mins

Task.WhenAll for parallel execution in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Task.WhenAll helps you run many tasks at the same time and wait for all of them to finish. This makes your program faster when doing multiple jobs.

When you want to download several files at once instead of one by one.
When you need to run multiple calculations in parallel to save time.
When you want to call several web services at the same time and wait for all results.
When you have many independent tasks that can run together without waiting for each other.
Syntax
C Sharp (C#)
Task.WhenAll(params Task[] tasks)
Task.WhenAll(IEnumerable<Task> tasks)

// For tasks that return results:
Task.WhenAll(params Task<TResult>[] tasks)
Task.WhenAll(IEnumerable<Task<TResult>> tasks)

You pass a list or array of tasks to Task.WhenAll.

It returns a single task that completes when all given tasks finish.

Examples
Waits for three tasks to finish running in parallel.
C Sharp (C#)
await Task.WhenAll(task1, task2, task3);
Waits for all tasks in a list and collects their results in an array.
C Sharp (C#)
var results = await Task.WhenAll(taskList);
Sample Program

This program runs three tasks at the same time. Each task waits for a different time and then returns a number. Task.WhenAll waits for all tasks to finish and collects their results. Then it prints each result.

C Sharp (C#)
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        Task<int> task1 = Task.Run(() => { Task.Delay(1000).Wait(); return 1; });
        Task<int> task2 = Task.Run(() => { Task.Delay(500).Wait(); return 2; });
        Task<int> task3 = Task.Run(() => { Task.Delay(1500).Wait(); return 3; });

        int[] results = await Task.WhenAll(task1, task2, task3);

        Console.WriteLine("Results:");
        foreach (var result in results)
        {
            Console.WriteLine(result);
        }
    }
}
OutputSuccess
Important Notes

If any task fails, Task.WhenAll will throw an exception containing all errors.

Use Task.WhenAll to improve performance by running tasks in parallel instead of one after another.

Summary

Task.WhenAll runs many tasks at the same time and waits for all to finish.

It returns results from all tasks as an array if tasks produce values.

It helps make programs faster by doing work in parallel.