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

Why Task.WhenAny for first completion in C Sharp (C#)? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could instantly react to the fastest task without messy code?

The Scenario

Imagine you start several tasks at once, like downloading files or fetching data from different servers. You want to proceed as soon as the first task finishes, but checking each one manually is tricky.

The Problem

Manually checking each task's completion means writing lots of code to poll or wait for each task. This is slow, messy, and easy to make mistakes, especially when tasks finish at unpredictable times.

The Solution

Task.WhenAny lets you wait for the first task to finish without extra checks. It simplifies your code and makes it efficient by immediately giving you the completed task to work with.

Before vs After
Before
while(true) {
  if(task1.IsCompleted) break;
  if(task2.IsCompleted) break;
  Thread.Sleep(100);
}
After
var firstDone = await Task.WhenAny(task1, task2);
What It Enables

You can react instantly to the first completed task, making your program faster and cleaner.

Real Life Example

When loading data from multiple sources, you can display the fastest response to the user without waiting for all sources to finish.

Key Takeaways

Manual checking of tasks is slow and error-prone.

Task.WhenAny waits for the first task to finish efficiently.

This makes your code simpler and more responsive.