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

Task.WhenAny for first completion in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Task.WhenAny for first completion
O(n)
Understanding Time Complexity

We want to understand how the time to get the first finished task grows as we add more tasks.

How does waiting for the first task to complete change when we have more tasks running?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


var tasks = new List<Task>();
for (int i = 0; i < n; i++)
{
    tasks.Add(Task.Run(() => DoWork()));
}
var firstFinished = await Task.WhenAny(tasks);
await firstFinished;
    

This code starts n tasks and waits for the first one to finish.

Identify Repeating Operations
  • Primary operation: Starting n tasks in a loop.
  • How many times: n times, once per task.
  • Waiting operation: Waiting for the first task to complete happens once.
How Execution Grows With Input

Starting tasks grows linearly with n, but waiting for the first to finish depends on the fastest task.

Input Size (n)Approx. Operations
10Start 10 tasks, wait for 1 to finish
100Start 100 tasks, wait for 1 to finish
1000Start 1000 tasks, wait for 1 to finish

Pattern observation: Starting tasks grows with n, but waiting time depends on the quickest task, not all.

Final Time Complexity

Time Complexity: O(n)

This means the work to start tasks grows with the number of tasks, but waiting stops as soon as the first finishes.

Common Mistake

[X] Wrong: "Waiting for the first task to finish takes as long as waiting for all tasks."

[OK] Correct: We only wait for the fastest task, so the wait time does not add up for all tasks.

Interview Connect

Understanding how waiting for the first task completion scales helps you reason about asynchronous code efficiency in real projects.

Self-Check

"What if we changed Task.WhenAny to Task.WhenAll? How would the time complexity change?"