Let’s go through Parallel Programming basics in C# — a way to run multiple operations concurrently to improve performance, especially on multi-core systems.
📌 1. What is Parallel Programming?
-
Parallel programming executes multiple operations simultaneously.
-
Useful for CPU-bound operations (e.g., computations, data processing).
-
C# provides built-in support through:
-
Parallel
class -
Task
/Task<T>
-
PLINQ (Parallel LINQ)
-
📌 2. Using the Parallel
Class
Parallel.For
using System;
using System.Threading.Tasks;
Parallel.For(0, 5, i =>
{
Console.WriteLine($"Task {i} running on thread {Task.CurrentId}");
});
-
Runs iterations in parallel
-
Automatically distributes work across threads
Parallel.ForEach
string[] names = { "Alice", "Bob", "Charlie" };
Parallel.ForEach(names, name =>
{
Console.WriteLine($"Processing {name} on thread {Task.CurrentId}");
});
- Iterates over a collection in parallel
📌 3. Using Tasks for Parallel Work
Task t1 = Task.Run(() => Console.WriteLine("Task 1"));
Task t2 = Task.Run(() => Console.WriteLine("Task 2"));
Task.WaitAll(t1, t2); // Wait for all tasks to complete
-
Tasks can be combined with
Task.WhenAll
orTask.WhenAny
-
Offers more flexibility than
Parallel
for complex scenarios
📌 4. Parallel LINQ (PLINQ)
-
PLINQ allows parallel queries on collections using LINQ
-
Syntax: add
.AsParallel()
to the collection
int[] numbers = { 1, 2, 3, 4, 5, 6 };
var evenNumbers = numbers.AsParallel()
.Where(n => n % 2 == 0)
.ToArray();
foreach (var n in evenNumbers)
Console.WriteLine(n); // 2, 4, 6
- Automatically utilizes multiple cores
📌 5. Important Considerations
-
Thread Safety: Shared data must be synchronized (locks,
Concurrent
collections). -
Overhead: Small tasks may be slower in parallel due to thread management.
-
Exceptions: Use
AggregateException
to handle multiple exceptions.
try
{
Parallel.For(0, 5, i =>
{
if (i == 3) throw new Exception("Error at 3");
});
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
Console.WriteLine(e.Message);
}
📌 6. Summary Table
Feature | Description |
---|---|
Parallel.For | Run a loop in parallel |
Parallel.ForEach | Parallel iteration over collections |
Tasks / Task | Flexible parallel operations with results |
PLINQ | Parallel LINQ queries on collections |
Key Considerations | Thread safety, exception handling, overhead |
✅ Tip:
-
Use Parallel.For/ForEach for CPU-bound loops
-
Use Tasks for flexible parallel operations
-
Use PLINQ for data processing with LINQ queries
-
Avoid parallelism for tiny, fast operations, as overhead may reduce performance