Consider the following C# code using Task.WhenAll to run tasks in parallel. What will be printed to the console?
using System; using System.Threading.Tasks; class Program { static async Task Main() { var task1 = Task.Delay(100).ContinueWith(_ => 1); var task2 = Task.Delay(50).ContinueWith(_ => 2); var results = await Task.WhenAll(task1, task2); Console.WriteLine(string.Join(",", results)); } }
Remember that Task.WhenAll returns results in the order of the tasks passed, not the order they complete.
The Task.WhenAll method returns an array of results in the same order as the tasks were passed in. Even though task2 finishes earlier, the results array keeps the order task1, task2. So the output is 1,2.
Choose the correct statement about Task.WhenAll in C#.
Think about how Task.WhenAll handles multiple tasks and their results.
Task.WhenAll runs tasks concurrently and waits for all to finish. It returns results in the order tasks were passed. It does not run tasks sequentially, nor does it return early or cancel others on failure.
Examine the code below. It throws an exception at runtime. What is the cause?
using System; using System.Threading.Tasks; class Program { static async Task Main() { var task1 = Task.FromException<int>(new InvalidOperationException("Error in task1")); var task2 = Task.Run(() => 42); var results = await Task.WhenAll(task1, task2); Console.WriteLine(string.Join(",", results)); } }
Think about how exceptions in tasks are handled when using Task.WhenAll.
If any task throws an exception, Task.WhenAll throws an AggregateException containing all exceptions from failed tasks. It does not ignore failures or cancel other tasks automatically.
Identify the correct syntax to run two async lambdas in parallel and await their results using Task.WhenAll.
Remember that Task.WhenAll expects tasks, not delegates or lambdas directly.
Task.WhenAll requires a collection of Task objects. Wrapping async lambdas inside Task.Run creates tasks to pass. Option A correctly creates and awaits the tasks.
Given the code below, how many elements does the results array contain after Task.WhenAll completes?
using System; using System.Threading.Tasks; class Program { static async Task Main() { Task<int> t1 = Task.FromResult(5); Task<int> t2 = Task.Run(() => 10); Task<int> t3 = Task.Delay(100).ContinueWith(_ => 15); var results = await Task.WhenAll(t1, t2, t3); Console.WriteLine(results.Length); } }
Count how many tasks are passed to Task.WhenAll.
Three tasks (t1, t2, t3) are passed to Task.WhenAll. The results array contains one element per task, so length is 3.