DEV Community

Cover image for C# - Parallel Asynchronous Operations with Task.WhenAny
Keyur Ramoliya
Keyur Ramoliya

Posted on

C# - Parallel Asynchronous Operations with Task.WhenAny

C# provides the Task.WhenAny method, which allows you to efficiently await the completion of the first task among a collection of tasks. This is particularly useful when you want to parallelize multiple asynchronous operations and process the result of the first one that completes.

Here's an example:

using System;
using System.Threading.Tasks;

public class Program
{
    public static async Task Main()
    {
        var task1 = SimulateAsyncOperation("Task 1", 2000);
        var task2 = SimulateAsyncOperation("Task 2", 3000);
        var task3 = SimulateAsyncOperation("Task 3", 1500);

        // Wait for the first completed task
        var completedTask = await Task.WhenAny(task1, task2, task3);

        // Handle the result of the completed task
        if (completedTask == task1)
        {
            Console.WriteLine("Task 1 completed first.");
        }
        else if (completedTask == task2)
        {
            Console.WriteLine("Task 2 completed first.");
        }
        else if (completedTask == task3)
        {
            Console.WriteLine("Task 3 completed first.");
        }
    }

    public static async Task SimulateAsyncOperation(string taskName, int delayMilliseconds)
    {
        await Task.Delay(delayMilliseconds);
        Console.WriteLine($"{taskName} completed after {delayMilliseconds} ms.");
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, we create three asynchronous tasks using SimulateAsyncOperation, each with a different delay. We then use Task.WhenAny to await the first completed task and process the result.

This technique is valuable in scenarios where you want to perform multiple asynchronous operations concurrently and act on the result of the first operation that finishes, which can help improve the overall responsiveness and efficiency of your code.

Top comments (0)