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.
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.
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.
var firstFinished = await Task.WhenAny(task1, task2, task3);
Task first = await Task.WhenAny(tasksArray);
This program starts three tasks that finish after different delays. It waits for the first one to finish and prints its result.
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); } }
Task.WhenAny does not cancel other tasks; they keep running.
You can check which task finished first by comparing the returned task.
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.
Task.WhenAny do in C#?Task.WhenAny with two tasks task1 and task2?var task1 = Task.Delay(3000).ContinueWith(_ => "Task1 done"); var task2 = Task.Delay(1000).ContinueWith(_ => "Task2 done"); var first = await Task.WhenAny(task1, task2); Console.WriteLine(await first);
Task.WhenAny:
var task1 = Task.Delay(2000); var task2 = Task.Delay(1000); var first = Task.WhenAny(task1, task2); Console.WriteLine(await first.Result);
taskA (2s delay), taskB (1s delay), and taskC (3s delay). You want to print the result of the first completed task and then cancel the other two tasks. Which code snippet correctly achieves this?Pass the test and this pattern moves unknown