C#
Task.WhenAny
Learn to await the first to finish with Task.WhenAny.
Task.WhenAny
Task.WhenAny waits until the first of several Tasks finishes. The returned Task contains the Task that completed. Example: Task<int> first = await Task.WhenAny(t1, t2);. Here first is the first Task to finish; you can read its result with await first.
It is useful in race scenarios: picking the faster of two responses. The losing Tasks keep running in the background; cancelling them is your responsibility.
Using WhenAny
WhenAny returns a Task, not a value directly. For example await Task.WhenAny(t1, t2) returns a Task that tells you which task finished. To get the value you also await that task: int val = await first;.
Cleaner style: first var first = await Task.WhenAny(t1, t2);, then int val = await first;. This is more readable, especially with cancellable work.
Exercise Get the first finisher with WhenAny
Define two methods: static Task<int> Source1() and static Task<int> Source2(). Both should return Task.FromResult(15);. Make Main a static async Task Main. Get the first finisher with Task<int> first = await Task.WhenAny(Source1(), Source2());, read its value with int val = await first; and print with Console.WriteLine(val);.
Show example solution
return Task.FromResult(15);. Make Main static async Task Main() and write Task<int> first = await Task.WhenAny(Source1(), Source2()); int val = await first; Console.WriteLine(val);
Example solution:
using System;
using System.Threading.Tasks;
class Program
{
static Task<int> Source1()
{
return Task.FromResult(15);
}
static Task<int> Source2()
{
return Task.FromResult(15);
}
static async Task Main()
{
Task<int> first = await Task.WhenAny(Source1(), Source2());
int val = await first;
Console.WriteLine(val);
}
}
Test yourself
-
Match WhenAll vs WhenAny
- WhenAll
- Waits for all Tasks
- WhenAny
- Waits for the first Task
- Task.FromResult
- Makes a ready-result Task
- Task.Run
- Sends work to the pool
-
What does WhenAny return?
- It returns the value directly
- It returns void
- It returns the first Task that completed
- It returns all results as an array
Show answer
It returns the first Task that completed — Correct. WhenAny returns the first Task that completed.
-
Complete the WhenAny call
Task<int> first = await Task.____(t1, t2);
Show answer
Task<int> first = await Task.WhenAny(t1, t2);
Next lesson: CancellationToken