Skip to main content

How to Wait for the First of Several Tasks to Finish with Task.WhenAny in C#

· 8 min read
Jagdish Kumawat
Founder @ Dewiride

await Task.WhenAny(a, b) waits until the first of several tasks has finished, and gives you that task. The others keep running, so what happens to them is up to you.

Microsoft's reference for Task.WhenAny: Creates a task that will complete when any of the supplied tasks have completed. A task is work that finishes later, such as a download or a delay, and await waits for it to finish. WhenAny returns a task too, and the reference describes what it holds: A new task that represents the completion of one of the supplied tasks. Its Result is the task that completed first. So await Task.WhenAny(...) gives you a task, the winner, and awaiting that one gives you its value.

Syntax​

Syntax
Task<T> <first> = await Task.WhenAny(<task1>, <task2>);
T <value> = await <first>;
PartWhat it is
<task1>, <task2>Tasks that are already running. WhenAny also takes more than two, or an array of tasks
Task.WhenAny(...)Returns a task that finishes as soon as one of them has finished
await Task.WhenAny(...)Waits for that moment and gives you the task that finished first
Task<T>The type of the tasks, such as Task<string> for tasks that return a string
await <first>Gets the value of the task that finished first

The Example​

A console app called TaskWhenAny starts two pretend deliveries at the same time: the North shop takes 3 seconds and the South shop 1. It waits only for the first one to arrive, prints which shop it was and how long that took, and then checks whether the other one has arrived too.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n TaskWhenAny
cd TaskWhenAny
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/TaskWhenAny/TaskWhenAny.csproj:
Determining projects to restore...
Restored /Users/you/source/TaskWhenAny/TaskWhenAny.csproj (in 44 ms).
Restore succeeded.

dotnet new console -n TaskWhenAny creates a folder named TaskWhenAny with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or TaskWhenAny.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First start both deliveries:

Program.cs (start two deliveries)
using System.Diagnostics;

// Two shops start delivering at the same time. One takes 3 seconds, the other 1.
Stopwatch watch = Stopwatch.StartNew();
Task<string> north = DeliverAsync("North shop", 3);
Task<string> south = DeliverAsync("South shop", 1);

Stopwatch comes from the System.Diagnostics namespace, hence the using line, and Stopwatch.StartNew() starts measuring time. Each call to DeliverAsync starts a delivery and hands back its Task<string> without waiting for it, so both deliveries run at the same time.

Then wait for the first one:

Program.cs (wait for the first)
// Wait only until the first of the two has finished.
Task<string> first = await Task.WhenAny(north, south);
Console.WriteLine($"First: {await first} after {watch.Elapsed.TotalSeconds:F1} seconds");
Console.WriteLine($"Is the North shop done too? {north.IsCompleted}");

await Task.WhenAny(north, south) waits until one of the two has finished and returns that task, so first is either north or south. await first gets its string. watch.Elapsed.TotalSeconds is the time since the stopwatch started, :F1 prints it with one decimal place, and north.IsCompleted says whether the North shop's task has finished.

Last, the pretend delivery:

Program.cs (the pretend delivery)
// Pretends to deliver something that takes a few seconds, then returns the shop's name.
static async Task<string> DeliverAsync(string shop, int seconds)
{
await Task.Delay(TimeSpan.FromSeconds(seconds));
return shop;
}

await Task.Delay(...) waits for the given number of seconds, and then the method returns the shop's name.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
First: South shop after 1.0 seconds
Is the North shop done too? False

macOS-style terminal window titled Terminal — TaskWhenAny showing dotnet run printing First: South shop after 1.0 seconds, and Is the North shop done too? False

The South shop finished first, after 1.0 seconds, and WhenAny returned its task right then, without waiting for the North shop's 3 seconds. That's why north.IsCompleted printed False: the North shop was still on its way.

The Complete File​

macOS-style code window titled Program.cs — TaskWhenAny showing a Stopwatch, two DeliverAsync tasks for the North shop and the South shop taking 3 and 1 seconds, await Task.WhenAny returning the first one to finish, and DeliverAsync waiting with Task.Delay before it returns the shop's name

Program.cs
using System.Diagnostics;

// Two shops start delivering at the same time. One takes 3 seconds, the other 1.
Stopwatch watch = Stopwatch.StartNew();
Task<string> north = DeliverAsync("North shop", 3);
Task<string> south = DeliverAsync("South shop", 1);

// Wait only until the first of the two has finished.
Task<string> first = await Task.WhenAny(north, south);
Console.WriteLine($"First: {await first} after {watch.Elapsed.TotalSeconds:F1} seconds");
Console.WriteLine($"Is the North shop done too? {north.IsCompleted}");

// Pretends to deliver something that takes a few seconds, then returns the shop's name.
static async Task<string> DeliverAsync(string shop, int seconds)
{
await Task.Delay(TimeSpan.FromSeconds(seconds));
return shop;
}

A Time Limit with Task.Delay​

WhenAny can also give a task a time limit: race it against Task.Delay, which, in the reference's words, Creates a task that completes after a specified time interval. If the delay finishes first, the time is up:

Program.cs (a time limit)
// Give each delivery 2 seconds. Whichever finishes first, the delivery or the delay, wins.
await DeliverWithinAsync("Quick shop", 1);
await DeliverWithinAsync("Slow shop", 5);

static async Task DeliverWithinAsync(string shop, int seconds)
{
Task<string> delivery = DeliverAsync(shop, seconds);
Task limit = Task.Delay(TimeSpan.FromSeconds(2));

Task finished = await Task.WhenAny(delivery, limit);
if (finished == delivery)
Console.WriteLine($"{await delivery}: delivered in time");
else
Console.WriteLine($"{shop}: gave up after 2 seconds");
}

static async Task<string> DeliverAsync(string shop, int seconds)
{
await Task.Delay(TimeSpan.FromSeconds(seconds));
return shop;
}
Output
Quick shop: delivered in time
Slow shop: gave up after 2 seconds

finished == delivery checks which of the two tasks won: WhenAny returns one of the tasks you passed in. The quick shop's 1 second beat the 2-second limit, and the slow shop's 5 seconds didn't, so the program gave up on it after 2 seconds.

Common Mistakes​

MistakeWhat happensDo this instead
Expecting await Task.WhenAny to give the valuestring first = await Task.WhenAny(north, south); didn't build: error CS0029: Cannot implicitly convert type 'System.Threading.Tasks.Task<string>' to 'string'Keep the task, then await it: Task<string> first = await Task.WhenAny(north, south); and await first
Expecting the other tasks to stopAfter WhenAny returned the South shop, the North shop still printed North shop delivered, and north.IsCompleted then printed True. The reference: In every overload of Task.WhenAny(), when the method returns the first completed task, the other tasks will continue running until completion, even if any of them completed in the Canceled or Faulted state.If you don't want them to finish, do what the reference suggests: you can cancel all the remaining tasks once the first task completes.
Expecting WhenAny to throw when the first task failsThe first task to finish threw The van broke down., but await Task.WhenAny(...) returned normally, and first.IsFaulted printed True. The reference: The returned task always ends in the RanToCompletion state with its Result set to the first task to complete. This is true even if the first task to complete ended in the Canceled or Faulted state.Await the winner inside try and catch: await first threw, and the catch printed await first threw: The van broke down.

FAQ​

What's the difference between Task.WhenAny and Task.WhenAll?​

WhenAny finishes when the first task has finished, and gives you that task. WhenAll waits for every task. Its reference: Creates a task that will complete when all of the supplied tasks have completed. Use WhenAny when the first result is enough, or for a time limit, and WhenAll when you need all of them.

How do I know which task finished first?​

Compare the task WhenAny returned with the tasks you passed in, as the time limit above does with finished == delivery. In the main example, await first printed South shop, so first was the south task.

Conclusion​

await Task.WhenAny(a, b) waits for the first of several tasks to finish and gives you that task. Await it again to get its value, or to see its exception. The other tasks keep running, so cancel them when you don't need them. Race a task against Task.Delay to give it a time limit.

Additional Resources​