Parallel.ForEach, PLINQ
Run work in parallel with Parallel.ForEach and build parallel pipelines with PLINQ (AsParallel, WithDegreeOfParallelism, AsOrdered).
Why parallel loops
Goal: Use the CPU better.
- Parallel.ForEach: action per item
- PLINQ: parallel query with operators
- Control degree of parallelism
- Be careful with side-effects
Parallel.ForEach basics
Parallel.ForEach spreads iterations across threads; each item runs the given action.
using System;
using System.Threading.Tasks;
public class Program
{
public static void Main(string[] args)
{
int[] data = new int[] { 1, 2, 3, 4, 5, 6 };
// Runs iterations concurrently on thread pool
Parallel.ForEach(data, x =>
{
int y = x * x; // small CPU work
Console.WriteLine("x=" + x + " y=" + y + " on " + Environment.CurrentManagedThreadId);
});
}
}
All lessons in this course
- Parallel.ForEach, PLINQ
- Producer/consumer with Channels (overview)
- Throughput vs latency trade-offs