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

Task.WhenAny for first completion in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Task.WhenAny helps you wait for the first task to finish among many. It lets your program continue as soon as one task is done.

You start multiple downloads and want to use the first file that finishes.
You ask several servers for data and want to process the fastest reply.
You run multiple calculations and want to get the earliest result.
You want to respond quickly when any user action happens among many options.
Syntax
C Sharp (C#)
Task<Task> Task.WhenAny(params Task[] tasks);

It returns a task that completes when any of the given tasks completes.

The result is the task that finished first.

Examples
Waits until one of the three tasks finishes, then returns that task.
C Sharp (C#)
var firstFinished = await Task.WhenAny(task1, task2, task3);
Waits for the first task in an array to complete.
C Sharp (C#)
Task first = await Task.WhenAny(tasksArray);
Sample Program

This program starts three tasks that finish after different delays. It waits for the first one to finish and prints its result.

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

class Program
{
    static async Task Main()
    {
        Task<string> task1 = Task.Delay(3000).ContinueWith(_ => "Task 1 done");
        Task<string> task2 = Task.Delay(1000).ContinueWith(_ => "Task 2 done");
        Task<string> task3 = Task.Delay(2000).ContinueWith(_ => "Task 3 done");

        Task<string> firstFinished = await Task.WhenAny(task1, task2, task3);

        Console.WriteLine(await firstFinished);
    }
}
OutputSuccess
Important Notes

Task.WhenAny does not cancel other tasks; they keep running.

You can check which task finished first by comparing the returned task.

Summary

Task.WhenAny waits for the first task to complete among many.

It returns the task that finished first.

Use it to respond quickly to the earliest result.