Parallel Programming in .NET
Parallel programming lets you take advantage of multiple CPU cores to improve performance and responsiveness. The .NET runtime provides a rich set of APIs that simplify writing concurrent code.
Key Concepts
- Task Parallel Library (TPL) – high‑level abstractions for parallelism.
- Parallel Class – simple parallel loops and invocations.
- PLINQ – Parallel LINQ for data‑parallel queries.
- async/await – asynchronous programming with lightweight tasks.
- Dataflow – pipeline‑style processing with
System.Threading.Tasks.Dataflow
.
Parallel Class
The Parallel
class provides static methods for parallel loops and invokes.
using System;
using System.Threading.Tasks;
class Example
{
static void Main()
{
Parallel.For(0, 10, i =>
{
Console.WriteLine($"Task {Task.CurrentId} processing index {i}");
});
}
}
Parallel LINQ (PLINQ)
Transform sequential LINQ queries into parallel ones with AsParallel
.
var numbers = Enumerable.Range(1, 1_000_000);
var parallelResult = numbers
.AsParallel()
.Where(n => n % 3 == 0)
.Select(n => n * n)
.Take(10)
.ToArray();
Task Parallel Library (TPL)
Use Task
for fine‑grained asynchronous work.
Task<int> ComputeAsync(int value)
{
return Task.Run(() =>
{
// Simulate intensive calculation
Thread.Sleep(500);
return value * value;
});
}
Dataflow (Pipeline)
Build robust processing pipelines with BufferBlock
and TransformBlock
.
using System.Threading.Tasks.Dataflow;
var input = new BufferBlock();
var square = new TransformBlock(x => x * x);
var print = new ActionBlock(x => Console.WriteLine(x));
input.LinkTo(square);
square.LinkTo(print);
for (int i = 1; i <= 5; i++) await input.SendAsync(i);
input.Complete();
await print.Completion;
Best Practices
- Avoid blocking calls inside parallel loops.
- Prefer
async
/await
for I/O‑bound work. - Limit degree of parallelism for CPU‑bound tasks (
ParallelOptions.MaxDegreeOfParallelism
). - Use cancellation tokens to support graceful shutdown.