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

Task.WhenAny for first completion in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Task.WhenAny for first completion
📖 Scenario: You are building a simple program that runs multiple tasks and wants to know which one finishes first.
🎯 Goal: Create three tasks that complete after different delays, then use Task.WhenAny to find and display the first task that finishes.
📋 What You'll Learn
Create three tasks with different delays
Use a variable to hold the first completed task
Use Task.WhenAny to get the first completed task
Print which task finished first
💡 Why This Matters
🌍 Real World
In real apps, you might start multiple operations and want to react as soon as one finishes, like loading data from multiple sources and using the fastest response.
💼 Career
Understanding Task.WhenAny is important for asynchronous programming in C#, which is common in web, desktop, and mobile app development.
Progress0 / 4 steps
1
Create three tasks with different delays
Create three tasks called task1, task2, and task3 that each delay for 3000, 2000, and 1000 milliseconds respectively using Task.Delay.
C Sharp (C#)
Need a hint?

Use Task.Delay(milliseconds) to create tasks that complete after a delay.

2
Create an array of tasks
Create an array called tasks that contains task1, task2, and task3.
C Sharp (C#)
Need a hint?

Use new Task[] { } to create an array of tasks.

3
Use Task.WhenAny to get the first completed task
Create a variable called firstFinished and assign it the result of await Task.WhenAny(tasks) inside an async method.
C Sharp (C#)
Need a hint?

Remember to make the Main method async to use await.

4
Print which task finished first
Print "Task 1 finished first" if firstFinished is task1, "Task 2 finished first" if it is task2, or "Task 3 finished first" if it is task3.
C Sharp (C#)
Need a hint?

Compare firstFinished with each task variable and print the matching message.