0Pricing
C# Academy · Lesson

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

  1. Parallel.ForEach, PLINQ
  2. Producer/consumer with Channels (overview)
  3. Throughput vs latency trade-offs
← Back to C# Academy