Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Awaiting Multiple Tasks | Async/Await Fundamentals and Converting Sync to Async
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
C# Async and Await Practice

bookAwaiting Multiple Tasks

Imagine you are preparing a meal with several dishes. If you cook each dish one after another, dinner will take much longer. But if you start multiple dishes at once and let them cook in parallel, you finish much sooner. The same idea applies to asynchronous programming: you can await tasks sequentially, waiting for each to finish before starting the next, or you can start them all at once and await their completion together. Choosing the right approach can significantly impact your application's performance and responsiveness.

Note
Definition

Task.WhenAll waits for all provided tasks to finish and aggregates their results.
Task.WhenAny completes when any one of the provided tasks finishes and returns the first completed task.

Program.cs

Program.cs

copy
1234567891011121314151617181920212223242526272829303132
using System; using System.Threading.Tasks; namespace ConsoleApp { public class Program { public static async Task Main(string[] args) { Console.WriteLine("Sequential execution:"); var result1 = await GetDataAsync("First"); var result2 = await GetDataAsync("Second"); Console.WriteLine(result1); Console.WriteLine(result2); Console.WriteLine("\nParallel execution:"); var task1 = GetDataAsync("First"); var task2 = GetDataAsync("Second"); var results = await Task.WhenAll(task1, task2); foreach (var result in results) { Console.WriteLine(result); } } public static async Task<string> GetDataAsync(string name) { await Task.Delay(1000); return $"Data from {name}"; } } }

When you await each task one after another, each must complete before the next begins. This is like cooking dishes in sequence. In contrast, by starting both tasks and then awaiting them together with Task.WhenAll, both operations run at the same time, much like cooking multiple dishes simultaneously. This makes your program more efficient when the tasks are independent.

Task.WhenAll lets you wait for all tasks to complete before continuing, returning their results as an array. If you only care about the first task to finish, you can use Task.WhenAny, which returns as soon as any task completes. Use Task.WhenAll when you need all results, and Task.WhenAny when you want to act on the quickest result and possibly cancel or ignore the others.

using System;
using System.Threading.Tasks;

namespace ConsoleApp
{
    public class TaskWhenAnyExample
    {
        public async Task RunAsync()
        {
            Task<string> task1 = GetDataAsync("A", 1000);
            Task<string> task2 = GetDataAsync("B", 2000);

            Task<string>[] tasks = new[] { task1, task2 };
            Task<string> firstFinished = await Task.WhenAny(tasks);

            Console.WriteLine($"First completed: {firstFinished.Result}");
        }

        private async Task<string> GetDataAsync(string name, int delay)
        {
            await Task.Delay(delay);
            return $"Result from {name}";
        }
    }
}

Running tasks in parallel can greatly improve performance, especially when tasks are independent and take time to complete, such as network requests or file operations. However, starting too many tasks at once can overload system resources, so you should consider the number and nature of the tasks. Sequential execution is sometimes necessary when tasks depend on each other's results. Use parallel execution for independent, time-consuming operations, and always handle exceptions and cancellations carefully to avoid resource leaks or unhandled errors.

1. What is the difference between Task.WhenAll and Task.WhenAny?

2. Why might you want to run tasks in parallel instead of sequentially?

3. What happens if one task in Task.WhenAll throws an exception?

question mark

What is the difference between Task.WhenAll and Task.WhenAny?

Select the correct answer

question mark

Why might you want to run tasks in parallel instead of sequentially?

Select the correct answer

question mark

What happens if one task in Task.WhenAll throws an exception?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 1. Capitolo 5

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Suggested prompts:

Can you explain the difference between Task.WhenAll and Task.WhenAny in more detail?

When should I use sequential execution instead of parallel execution?

What are some best practices for handling exceptions when running tasks in parallel?

bookAwaiting Multiple Tasks

Scorri per mostrare il menu

Imagine you are preparing a meal with several dishes. If you cook each dish one after another, dinner will take much longer. But if you start multiple dishes at once and let them cook in parallel, you finish much sooner. The same idea applies to asynchronous programming: you can await tasks sequentially, waiting for each to finish before starting the next, or you can start them all at once and await their completion together. Choosing the right approach can significantly impact your application's performance and responsiveness.

Note
Definition

Task.WhenAll waits for all provided tasks to finish and aggregates their results.
Task.WhenAny completes when any one of the provided tasks finishes and returns the first completed task.

Program.cs

Program.cs

copy
1234567891011121314151617181920212223242526272829303132
using System; using System.Threading.Tasks; namespace ConsoleApp { public class Program { public static async Task Main(string[] args) { Console.WriteLine("Sequential execution:"); var result1 = await GetDataAsync("First"); var result2 = await GetDataAsync("Second"); Console.WriteLine(result1); Console.WriteLine(result2); Console.WriteLine("\nParallel execution:"); var task1 = GetDataAsync("First"); var task2 = GetDataAsync("Second"); var results = await Task.WhenAll(task1, task2); foreach (var result in results) { Console.WriteLine(result); } } public static async Task<string> GetDataAsync(string name) { await Task.Delay(1000); return $"Data from {name}"; } } }

When you await each task one after another, each must complete before the next begins. This is like cooking dishes in sequence. In contrast, by starting both tasks and then awaiting them together with Task.WhenAll, both operations run at the same time, much like cooking multiple dishes simultaneously. This makes your program more efficient when the tasks are independent.

Task.WhenAll lets you wait for all tasks to complete before continuing, returning their results as an array. If you only care about the first task to finish, you can use Task.WhenAny, which returns as soon as any task completes. Use Task.WhenAll when you need all results, and Task.WhenAny when you want to act on the quickest result and possibly cancel or ignore the others.

using System;
using System.Threading.Tasks;

namespace ConsoleApp
{
    public class TaskWhenAnyExample
    {
        public async Task RunAsync()
        {
            Task<string> task1 = GetDataAsync("A", 1000);
            Task<string> task2 = GetDataAsync("B", 2000);

            Task<string>[] tasks = new[] { task1, task2 };
            Task<string> firstFinished = await Task.WhenAny(tasks);

            Console.WriteLine($"First completed: {firstFinished.Result}");
        }

        private async Task<string> GetDataAsync(string name, int delay)
        {
            await Task.Delay(delay);
            return $"Result from {name}";
        }
    }
}

Running tasks in parallel can greatly improve performance, especially when tasks are independent and take time to complete, such as network requests or file operations. However, starting too many tasks at once can overload system resources, so you should consider the number and nature of the tasks. Sequential execution is sometimes necessary when tasks depend on each other's results. Use parallel execution for independent, time-consuming operations, and always handle exceptions and cancellations carefully to avoid resource leaks or unhandled errors.

1. What is the difference between Task.WhenAll and Task.WhenAny?

2. Why might you want to run tasks in parallel instead of sequentially?

3. What happens if one task in Task.WhenAll throws an exception?

question mark

What is the difference between Task.WhenAll and Task.WhenAny?

Select the correct answer

question mark

Why might you want to run tasks in parallel instead of sequentially?

Select the correct answer

question mark

What happens if one task in Task.WhenAll throws an exception?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 1. Capitolo 5
some-alt