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

Task.WhenAll for parallel execution in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Task.WhenAll for parallel execution
O(1)
Understanding Time Complexity

When running multiple tasks at the same time, it is important to understand how the total time grows as we add more tasks.

We want to know how the overall execution time changes when using Task.WhenAll to run tasks in parallel.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


async Task RunMultipleTasksAsync(List<Func<Task>> taskFactories)
{
    var tasks = taskFactories.Select(factory => factory()).ToList();
    await Task.WhenAll(tasks);
}
    

This code runs many tasks in parallel and waits for all of them to finish.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Starting each task once by calling each factory function.
  • How many times: Once per task, so as many times as there are tasks (n).
  • Parallel wait: Task.WhenAll waits for all tasks to complete simultaneously.
How Execution Grows With Input

When tasks run truly in parallel, the total time depends mostly on the longest single task, not the number of tasks.

Input Size (n)Approx. Operations
10Starts 10 tasks, waits for all to finish together.
100Starts 100 tasks, still waits roughly as long as the longest task.
1000Starts 1000 tasks, total wait time depends on longest task, not sum.

Pattern observation: Total wait time grows with the longest task duration, not with the number of tasks.

Final Time Complexity

Time Complexity: O(1)

This means the total waiting time does not increase as you add more tasks, assuming they run in parallel.

Common Mistake

[X] Wrong: "Adding more tasks always makes the program take longer because it waits for each one in order."

[OK] Correct: Task.WhenAll waits for all tasks at the same time, so the total time depends on the slowest task, not the number of tasks.

Interview Connect

Understanding how parallel tasks affect total time helps you write efficient programs and explain your reasoning clearly in interviews.

Self-Check

"What if the tasks are not truly parallel but run one after another? How would the time complexity change?"