The Task Parallel Library (TPL) is a set of APIs in System.Threading.Tasks that simplifies parallel and concurrent programming in .NET. It manages threads for you through the thread pool, so you work with tasks and data instead of raw threads. Main components 1. Task and Task<T> Represent asynchronous or parallel units of work, with results, exceptions and cancellation. Task<int> t = Task.Run(() => ExpensiveCalculation()); int result = await t; 2. Parallel class (data parallelism for CPU-bound work) Parallel.For(0, images.Length, i => images[i] = ApplyFilter(images[i])); Parallel.ForEach(files, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, file => ProcessFile(file)); // .NET 6+: async-friendly, for I/O-bound work with limited concurrency await Parallel.ForEachAsync(urls, new ParallelOptions { MaxDegreeOfParallelism = 8 }, async (url, ct) => await DownloadAsync(url, ct)); Parallel.Invoke(() => LoadCustomers(), () => LoadProducts()); // run several actions concurrently 3. PLINQ (Parallel LINQ) var primes = numbers.AsParallel().Where(IsPrime).ToList(); Spreads LINQ queries across cores; use AsOrdered() if order matters and WithDegreeOfParallelism to limit threads. 4. Coordination tools Task.WhenAll, Task.WhenAny, continuations, CancellationToken and CancellationTokenSource, concurrent collections (ConcurrentDictionary, BlockingCollection), and TPL Dataflow (System.Threading.Tasks.Dataflow) for producer-consumer pipelines. Benefits - Uses all CPU cores efficiently for CPU-bound workloads. - Higher-level, safer abstractions than manual threads. - Built-in partitioning, work stealing, cancellation and exception aggregation (AggregateException). When to use what - CPU-bound work on collections (image processing, calculations, parsing): Parallel.For/ForEach or PLINQ. - I/O-bound work (HTTP, database): async/await, and Parallel.ForEachAsync or Task.WhenAll to run several operations concurrently with a concurrency limit. Pitfalls - Shared mutable state causes race conditions; use thread-safe collections, locks or avoid sharing. - Parallelism has overhead; for small workloads a normal loop can be faster. Measure first. - Avoid Parallel.For in ASP.NET Core request handlers for typical requests: the server already processes many requests concurrently, and extra parallelism can reduce overall throughput. - Avoid blocking calls inside parallel loops; do not use Parallel.ForEach with async lambdas (use Parallel.ForEachAsync).
Ravindra Wadile · · 0 likes