What if you could instantly react to the fastest task without messy code?
Why Task.WhenAny for first completion in C Sharp (C#)? - Purpose & Use Cases
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.
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.
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.
while(true) { if(task1.IsCompleted) break; if(task2.IsCompleted) break; Thread.Sleep(100); }
var firstDone = await Task.WhenAny(task1, task2);
You can react instantly to the first completed task, making your program faster and cleaner.
When loading data from multiple sources, you can display the fastest response to the user without waiting for all sources to finish.
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.