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

Task.WhenAll for parallel execution in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Task.WhenAll for parallel execution
📖 Scenario: You are building a simple program that fetches data from multiple sources at the same time. This helps save time because the program does not wait for one source to finish before starting the next.
🎯 Goal: Learn how to use Task.WhenAll to run multiple tasks in parallel and wait for all of them to complete.
📋 What You'll Learn
Create three tasks that simulate data fetching with delays
Use a configuration variable to set the delay time
Use Task.WhenAll to run all tasks in parallel
Print the results after all tasks complete
💡 Why This Matters
🌍 Real World
Fetching data from multiple web services or databases at the same time to improve performance.
💼 Career
Understanding parallel execution with Task.WhenAll is important for building efficient and responsive applications in C#.
Progress0 / 4 steps
1
Create three tasks simulating data fetching
Create three Task<string> variables named task1, task2, and task3. Each task should simulate fetching data by returning a string after a delay. Use Task.Delay with 1000 milliseconds inside each task to simulate the delay. Use async lambdas for the tasks.
C Sharp (C#)
Need a hint?

Use Task.Run with an async lambda that awaits Task.Delay(1000) and then returns a string.

2
Add a delay configuration variable
Add an int variable named delayTime and set it to 1000. Then update the Task.Delay calls inside task1, task2, and task3 to use delayTime instead of the fixed number.
C Sharp (C#)
Need a hint?

Declare int delayTime = 1000; before the tasks. Replace Task.Delay(1000) with Task.Delay(delayTime) inside each task.

3
Use Task.WhenAll to run tasks in parallel
Use Task.WhenAll with task1, task2, and task3 to run all tasks in parallel and wait for all to complete. Store the result in a variable named results of type string[]. Use await with Task.WhenAll.
C Sharp (C#)
Need a hint?

Use string[] results = await Task.WhenAll(task1, task2, task3); to run all tasks and get their results.

4
Print the results after all tasks complete
Use a foreach loop to print each string in the results array. Use Console.WriteLine inside the loop to display each result.
C Sharp (C#)
Need a hint?

Use foreach (string result in results) { Console.WriteLine(result); } to print each result.