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

Task.WhenAll for parallel execution in C Sharp (C#) - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Task.WhenAll for parallel execution
Start multiple tasks
Tasks run in parallel
Wait for all tasks to complete
Continue after all tasks finish
Start several tasks at once, let them run at the same time, then wait until all are done before moving on.
Execution Sample
C Sharp (C#)
async Task Example()
{
  var task1 = Task.Delay(1000);
  var task2 = Task.Delay(2000);
  await Task.WhenAll(task1, task2);
  Console.WriteLine("All done");
}
Starts two delay tasks in parallel and waits for both to finish before printing.
Execution Table
StepActionTask1 StatusTask2 StatusOutput
1Start task1 and task2RunningRunning
2Wait for tasks to completeRunningRunning
3task1 completes after 1sCompletedRunning
4task2 completes after 2sCompletedCompleted
5Continue after all tasks doneCompletedCompletedAll done
💡 Both tasks completed, so Task.WhenAll finishes and program continues.
Variable Tracker
VariableStartAfter Step 1After Step 3After Step 4Final
task1nullRunningCompletedCompletedCompleted
task2nullRunningRunningCompletedCompleted
Key Moments - 2 Insights
Why does the program wait before printing "All done"?
Because Task.WhenAll waits until both task1 and task2 are completed, as shown in execution_table steps 2 to 5.
Do task1 and task2 run one after another or at the same time?
They run in parallel, both start immediately at step 1 and run simultaneously until they finish.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the status of task1 at step 3?
ARunning
BCompleted
CNot started
DFaulted
💡 Hint
Check the 'Task1 Status' column at step 3 in the execution_table.
At which step do both tasks complete?
AStep 4
BStep 3
CStep 2
DStep 5
💡 Hint
Look for when both 'Task1 Status' and 'Task2 Status' show 'Completed' in the execution_table.
If task2 took only 500ms instead of 2000ms, when would Task.WhenAll complete?
AAfter 2 seconds
BAfter 500ms
CAfter 1 second
DImmediately
💡 Hint
Task.WhenAll waits for all tasks; the longest task duration controls completion time.
Concept Snapshot
Task.WhenAll runs multiple tasks at the same time.
It waits until all tasks finish before continuing.
Use await Task.WhenAll(task1, task2, ...).
This helps do work in parallel efficiently.
The program pauses at await until all tasks complete.
Full Transcript
This example shows how Task.WhenAll runs tasks in parallel and waits for all to finish. First, two tasks start running at the same time. Task1 finishes after 1 second, task2 after 2 seconds. The program waits until both are done, then prints "All done". This lets you do multiple things at once and continue only when all are ready.