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

Task.WhenAll for parallel execution in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does Task.WhenAll do in C#?

Task.WhenAll waits for multiple tasks to complete in parallel and returns a single task that finishes when all the given tasks are done.

Click to reveal answer
beginner
How do you use Task.WhenAll to run two tasks at the same time?

You create two tasks and pass them to Task.WhenAll. It runs both tasks in parallel and waits for both to finish.

var task1 = Task.Run(() => DoWork1());
var task2 = Task.Run(() => DoWork2());
await Task.WhenAll(task1, task2);
Click to reveal answer
intermediate
What type does Task.WhenAll return when given tasks with results?

When given tasks that return results (like Task<int>), Task.WhenAll returns a Task<T[]> where T[] is an array of all results.

Click to reveal answer
intermediate
What happens if one of the tasks passed to Task.WhenAll throws an exception?

Task.WhenAll will complete with an exception. The exception contains all exceptions from the tasks that failed.

Click to reveal answer
beginner
Why use Task.WhenAll instead of awaiting tasks one by one?

Using Task.WhenAll runs tasks in parallel, saving time. Awaiting tasks one by one runs them sequentially, which is slower.

Click to reveal answer
What does Task.WhenAll return when given multiple Task objects?
AAn array of tasks
BThe result of the first task that finishes
CA single <code>Task</code> that completes when all tasks finish
DA boolean indicating if all tasks succeeded
If you want to get results from multiple Task<int> tasks, what type does Task.WhenAll return?
A<code>Task&lt;int&gt;</code>
B<code>Task&lt;int[]&gt;</code>
C<code>int[]</code>
D<code>Task</code>
What happens if one task throws an exception when using Task.WhenAll?
AThe returned task completes with an exception containing all errors
BThe exception is ignored
COnly the first exception is thrown immediately
DThe program crashes
Why is Task.WhenAll better than awaiting tasks one after another?
AIt runs tasks in parallel, saving time
BIt runs tasks sequentially, which is faster
CIt only runs the first task
DIt cancels all tasks automatically
Which of these is a correct way to use Task.WhenAll?
Aawait task1; await task2;
BTask.WhenAll(task1, task2);
CTask.WaitAll(task1, task2);
Dawait Task.WhenAll(task1, task2);
Explain how Task.WhenAll helps run multiple tasks in parallel and why this is useful.
Think about waiting for many things to finish together instead of one after another.
You got /3 concepts.
    Describe what happens when one or more tasks fail while using Task.WhenAll.
    Consider how errors from multiple sources are reported together.
    You got /3 concepts.