Sequential vs Parallel Async Tasks
When you work with asynchronous programming, you often have a choice: should you run tasks one after the other, or launch them all at once? Think of it like washing dishes. If you scrub, rinse, and dry each plate before starting the next, that's sequential execution. If you gather some friends and each of you works on a plate at the same time, that's parallel execution. In C#, async code gives you the flexibility to choose either pattern, and the right choice can depend on your goals and the resources available.
The degree of parallelism is the maximum number of tasks or operations allowed to run at the same time. In async code, controlling the degree of parallelism helps balance performance and resource usage.
Program.cs
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051using System; using System.Diagnostics; using System.Threading.Tasks; using System.Collections.Generic; namespace ConsoleApp { public class Program { public static async Task Main(string[] args) { Console.WriteLine("Sequential execution:"); var sw = Stopwatch.StartNew(); await RunSequentialAsync(); sw.Stop(); Console.WriteLine($"Total time: {sw.ElapsedMilliseconds} ms\n"); Console.WriteLine("Parallel execution:"); sw.Restart(); await RunParallelAsync(); sw.Stop(); Console.WriteLine($"Total time: {sw.ElapsedMilliseconds} ms"); } public static async Task WashDishAsync(int dishNumber) { Console.WriteLine($"Start washing dish {dishNumber}"); await Task.Delay(1000); // Simulate washing time Console.WriteLine($"Finished washing dish {dishNumber}"); } public static async Task RunSequentialAsync() { for (int i = 1; i <= 3; i++) { await WashDishAsync(i); } } public static async Task RunParallelAsync() { var tasks = new List<Task>(); for (int i = 1; i <= 3; i++) { tasks.Add(WashDishAsync(i)); } await Task.WhenAll(tasks); } } }
When you run tasks sequentially, each one waits for the previous to finish before starting. In the dishwashing example, the total time is roughly the sum of the time for each dish. When you run them in parallel, all tasks start together, and the total time is closer to the longest single task. Parallel execution can dramatically improve performance if your tasks are independent and resources allow. However, sequential execution might be better if tasks depend on each other, or if running too many at once could overwhelm your system or an external service.
LimitingParallelism.cs
12345678910111213141516171819202122232425262728293031323334353637using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp { public class LimitingParallelism { public async Task WashDishesWithLimitAsync(int dishCount, int maxParallel) { using (SemaphoreSlim semaphore = new SemaphoreSlim(maxParallel)) { var tasks = new List<Task>(); for (int i = 1; i <= dishCount; i++) { await semaphore.WaitAsync(); int dishNumber = i; tasks.Add(Task.Run(async () => { try { Console.WriteLine($"Washing dish {dishNumber}"); await Task.Delay(1000); } finally { semaphore.Release(); } })); } await Task.WhenAll(tasks); } } } }
Running too many tasks in parallel can cause problems like using up all your system memory or overwhelming a database or web service. To avoid this, you can limit how many tasks run at once, as shown above. This is especially important when working with large collections or resource-intensive operations.
1. When is it better to run tasks sequentially rather than in parallel?
2. How can you control the number of concurrent async tasks?
3. What is a risk of running too many tasks in parallel?
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo
Incrível!
Completion taxa melhorada para 5.56
Sequential vs Parallel Async Tasks
Deslize para mostrar o menu
When you work with asynchronous programming, you often have a choice: should you run tasks one after the other, or launch them all at once? Think of it like washing dishes. If you scrub, rinse, and dry each plate before starting the next, that's sequential execution. If you gather some friends and each of you works on a plate at the same time, that's parallel execution. In C#, async code gives you the flexibility to choose either pattern, and the right choice can depend on your goals and the resources available.
The degree of parallelism is the maximum number of tasks or operations allowed to run at the same time. In async code, controlling the degree of parallelism helps balance performance and resource usage.
Program.cs
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051using System; using System.Diagnostics; using System.Threading.Tasks; using System.Collections.Generic; namespace ConsoleApp { public class Program { public static async Task Main(string[] args) { Console.WriteLine("Sequential execution:"); var sw = Stopwatch.StartNew(); await RunSequentialAsync(); sw.Stop(); Console.WriteLine($"Total time: {sw.ElapsedMilliseconds} ms\n"); Console.WriteLine("Parallel execution:"); sw.Restart(); await RunParallelAsync(); sw.Stop(); Console.WriteLine($"Total time: {sw.ElapsedMilliseconds} ms"); } public static async Task WashDishAsync(int dishNumber) { Console.WriteLine($"Start washing dish {dishNumber}"); await Task.Delay(1000); // Simulate washing time Console.WriteLine($"Finished washing dish {dishNumber}"); } public static async Task RunSequentialAsync() { for (int i = 1; i <= 3; i++) { await WashDishAsync(i); } } public static async Task RunParallelAsync() { var tasks = new List<Task>(); for (int i = 1; i <= 3; i++) { tasks.Add(WashDishAsync(i)); } await Task.WhenAll(tasks); } } }
When you run tasks sequentially, each one waits for the previous to finish before starting. In the dishwashing example, the total time is roughly the sum of the time for each dish. When you run them in parallel, all tasks start together, and the total time is closer to the longest single task. Parallel execution can dramatically improve performance if your tasks are independent and resources allow. However, sequential execution might be better if tasks depend on each other, or if running too many at once could overwhelm your system or an external service.
LimitingParallelism.cs
12345678910111213141516171819202122232425262728293031323334353637using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp { public class LimitingParallelism { public async Task WashDishesWithLimitAsync(int dishCount, int maxParallel) { using (SemaphoreSlim semaphore = new SemaphoreSlim(maxParallel)) { var tasks = new List<Task>(); for (int i = 1; i <= dishCount; i++) { await semaphore.WaitAsync(); int dishNumber = i; tasks.Add(Task.Run(async () => { try { Console.WriteLine($"Washing dish {dishNumber}"); await Task.Delay(1000); } finally { semaphore.Release(); } })); } await Task.WhenAll(tasks); } } } }
Running too many tasks in parallel can cause problems like using up all your system memory or overwhelming a database or web service. To avoid this, you can limit how many tasks run at once, as shown above. This is especially important when working with large collections or resource-intensive operations.
1. When is it better to run tasks sequentially rather than in parallel?
2. How can you control the number of concurrent async tasks?
3. What is a risk of running too many tasks in parallel?
Obrigado pelo seu feedback!