Awaiting 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.
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
1234567891011121314151617181920212223242526272829303132using 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?
Danke für Ihr Feedback!
Fragen Sie AI
Fragen Sie AI
Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen
Großartig!
Completion Rate verbessert auf 5.56
Awaiting Multiple Tasks
Swipe um das Menü anzuzeigen
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.
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
1234567891011121314151617181920212223242526272829303132using 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?
Danke für Ihr Feedback!