Parallel Work: The Assembly Line

Parallel Work: The Assembly Line in C#: Hiring a second cook, as the previous two lessons showed, means managing people: hiring, firing, handing out keys,…

The Analogy: The Assembly Line

Hiring a second cook, as the previous two lessons showed, means managing people: hiring, firing, handing out keys, settling arguments over the storeroom. A factory owner facing ten thousand identical widgets does not hire and fire for each one. They build an assembly line: the work is divided into batches, a fixed crew of workers pulls from the queue, and when a worker finishes a batch they take the next one. Nobody is created or destroyed per widget, and the owner never thinks about individual workers at all.

Parallel.For, Parallel.ForEach and PLINQ are that assembly line. You describe the work — this range of numbers, this collection of files, this LINQ query — and the runtime decides how many workers to use, how to split the input, and how to rebalance when one batch turns out slower than the others. You give up control over who does what, and in exchange you stop writing thread bookkeeping.

The line has one strict entry requirement: the batches must be independent. If widget 500 needs the result of widget 499, there is no line to build, and no library can invent one. This is why the parallel toolkit is described as data parallelism — the same operation applied to many independent items — and why the first question is never "which API" but "are my items actually independent?"

There is also a toll at the gate. Splitting the input, dispatching batches, and merging results costs real time, so a line only pays off when each item carries enough work to dwarf the overhead. Ten thousand items that take a nanosecond each will run slower in parallel than in a plain for loop. The skill in this lesson is as much about recognising when not to build the line as about building it.


Syntax or Core Structure

using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        // 1. Parallel.For with partition-local accumulation
        long total = 0;
        Parallel.For(1, 1_000_001,
            () => 0L,                                     // localInit: per-partition seed
            (n, state, local) => local + n % 7,           // body: no shared writes
            local => Interlocked.Add(ref total, local));  // localFinally: merge once
        Console.WriteLine("sum of n%7 = " + total);

        // 2. Parallel.ForEach over a collection
        string[] words = { "alpha", "beta", "gamma", "delta" };
        ConcurrentDictionary<string, int> lengths = new();
        Parallel.ForEach(words, w => lengths[w] = w.Length);

        foreach (var pair in lengths.OrderBy(p => p.Key))
            Console.WriteLine(pair.Key + " = " + pair.Value);

        // 3. PLINQ - AsOrdered restores input order in the output
        int[] squares = Enumerable.Range(1, 8)
            .AsParallel()
            .AsOrdered()
            .Where(n => n % 2 == 0)
            .Select(n => n * n)
            .ToArray();
        Console.WriteLine("even squares: " + string.Join(", ", squares));
    }
}

Output:

sum of n%7 = 2999998
alpha = 5
beta = 4
delta = 5
gamma = 5
even squares: 4, 16, 36, 64

Every one of those lines is deterministic, but for three different reasons, and the reasons are the lesson.

The Parallel.For overload with localInit and localFinally is the shape from the threading lesson, done for you: each partition seeds its own long, accumulates into it with no synchronisation at all, and merges once at the end with a single Interlocked.Add. Four partitions means four interlocked operations, not a million. The simpler overload — Parallel.For(1, 1_000_001, n => total += n % 7) — compiles, runs, and produces a different wrong answer every time.

Parallel.ForEach writes into a ConcurrentDictionary, so no lock is needed, but the insertion order is whatever the workers happen to do. The OrderBy on the way out is what makes the output stable — and it is the same rule as reflection's member order: if unordered results are visible, sort them.

PLINQ's AsOrdered is the odd one out. By default a parallel query returns results in completion order, which is fast and unpredictable; AsOrdered asks the merge step to restore input order, which costs buffering. Without it, even squares could print as 36, 4, 64, 16.


Technical Depth: Where the Time Actually Goes

ToolBest forWatch out for
Parallel.ForCPU work over a numeric rangeNeeds localInit/localFinally for aggregates
Parallel.ForEachCPU work over a collectionUnordered results; body must be thread-safe
Parallel.ForEachAsyncMany concurrent I/O callsSet MaxDegreeOfParallelism or you flood the server
PLINQ (AsParallel)Query-shaped transforms and aggregatesOverhead beats you on cheap delegates
Task.WhenAllA handful of distinct async operationsNot a partitioner; you size the work yourself
Plain forSmall inputs, tiny bodiesOften genuinely the fastest option

The overhead is real

A parallel loop must partition the input, queue work to the pool, and join the results. That is on the order of microseconds — utterly invisible next to a body that parses a document, and catastrophic next to a body that adds two numbers. The rule of thumb: if a single iteration does not take at least a few microseconds, batch several items per iteration or do not parallelise at all. Measure before and after; parallel code that is slower is a common and embarrassing outcome.

Stopping early: Break versus Stop

ParallelLoopResult result = Parallel.For(0, items.Length, (i, state) =>
{
    if (items[i] is null) { state.Break(); return; }   // finish lower indices
    if (items[i] == target) { state.Stop(); return; }  // quit as soon as possible
    Process(items[i]);
});

if (!result.IsCompleted)
    Console.WriteLine("stopped at " + result.LowestBreakIteration);

Break means "no iteration above this one needs to run, but every lower one still does" — the right choice for an ordered search. Stop means "abandon everything as fast as possible" and is the right choice for "find any match". Neither is instantaneous: iterations already in flight run to completion, so the body must tolerate being called after you asked to stop. A plain return from the body only ends that iteration; it is continue, not break.

Exceptions arrive in a bundle

Several iterations can throw at once, so Parallel.* collects them into an AggregateException:

try { Parallel.ForEach(files, Process); }
catch (AggregateException ex)
{
    foreach (Exception inner in ex.Flatten().InnerExceptions)
        Console.WriteLine(inner.GetType().Name + ": " + inner.Message);
}

Flatten() matters because nested parallel loops produce nested aggregates. Cancellation is separate: ParallelOptions.CancellationToken surfaces as OperationCanceledException, not inside the aggregate.

False sharing

Two threads writing to counts[0] and counts[1] never race — but those slots almost certainly sit on the same 64-byte cache line, so every write invalidates the other core's copy. The result is a loop that is correct, lock-free, and slower than single-threaded. The fix is the same partition-local pattern: accumulate in a local variable and write to the shared array once.

Async is not parallel

Parallel.ForEach(urls, url => client.GetStringAsync(url).Result) blocks a pool thread per URL and can deadlock or exhaust the pool. For I/O, use Parallel.ForEachAsync with an explicit degree, or Task.WhenAll over a bounded batch. Parallelism is for burning CPU; asynchrony is for waiting without burning threads.


Real World Example: Counting Words Across Documents

A search indexer has to tally word frequencies across a corpus. Documents are independent, the per-document work is real, and the only shared thing is the final tally — the textbook case for an assembly line.

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static readonly string[] Documents =
    {
        "the ledger balances the ledger holds",
        "audit the ledger and audit the books",
        "the books balances audit report",
        "report the report and the ledger"
    };

    static void Main()
    {
        ConcurrentDictionary<string, int> counts = new(StringComparer.Ordinal);
        int wordsSeen = 0;

        ParallelOptions options = new ParallelOptions
        {
            MaxDegreeOfParallelism = Math.Min(4, Environment.ProcessorCount)
        };

        Parallel.ForEach(Documents, options, document =>
        {
            string[] words = document.Split(' ');
            Interlocked.Add(ref wordsSeen, words.Length);

            // Tally locally first, so the shared map is touched once per
            // distinct word instead of once per occurrence.
            Dictionary<string, int> local = new(StringComparer.Ordinal);
            foreach (string word in words)
                local[word] = local.GetValueOrDefault(word) + 1;

            foreach (KeyValuePair<string, int> entry in local)
                counts.AddOrUpdate(entry.Key, entry.Value, (_, running) => running + entry.Value);
        });

        Console.WriteLine("words seen: " + wordsSeen);
        Console.WriteLine("distinct:   " + counts.Count);

        foreach (KeyValuePair<string, int> pair in counts
            .OrderByDescending(p => p.Value)
            .ThenBy(p => p.Key, StringComparer.Ordinal)
            .Take(4))
        {
            Console.WriteLine(pair.Key.PadRight(9) + pair.Value);
        }
    }
}

Output:

words seen: 24
distinct:   8
the      7
ledger   4
audit    3
report   3

The tie between audit and report is why ThenBy is there. OrderByDescending alone would put them in whatever order the dictionary enumerated, which varies with insertion order, which varies with which worker finished first — a test that passes on your laptop and fails in CI. Any time parallel results are sorted, the sort must be total: a comparison that leaves ties unresolved leaves the output unpredictable.

The local Dictionary inside the body is the performance decision. Without it, the would hit the shared ConcurrentDictionary seven times, each hit taking a striped lock and possibly contending with another worker. With it, each document contributes one update per distinct word — 8 updates instead of 24 in this tiny corpus, and a far larger ratio on real documents where common words repeat hundreds of times. AddOrUpdate is what makes the merge safe: the read-modify-write happens inside the dictionary's own synchronisation, whereas counts[key] = counts[key] + n would reintroduce exactly the lost-update race that ++ had.

MaxDegreeOfParallelism deserves the explicit setting even though the default is usually fine. The default lets the pool grow, which is right for a batch job that owns the machine and wrong inside a web request, where every core spent on one user's report is a core not serving anybody else. Capping it at four keeps a background job from starving the foreground — and Math.Min keeps the cap from exceeding what the machine has.


Common Mistakes

  1. Accumulating into a shared variable from the body. total += x inside Parallel.For is a data race. Use the localInit/localFinally overload, or Interlocked, or a concurrent collection.
  2. Assuming the results come back in order. Parallel.ForEach and PLINQ produce completion order. Use AsOrdered, or sort on the way out with a total comparison.
  3. Parallelising a tiny body. Partitioning and merging cost more than the work, so the loop gets slower. Batch the items or leave the for loop alone.
  4. Using Parallel.ForEach for I/O. Blocking on .Result inside the body burns a pool thread per item. Use Parallel.ForEachAsync or Task.WhenAll.
  5. Catching the wrong exception type. Failures arrive as AggregateException; call Flatten() and inspect InnerExceptions.
  6. Expecting Break or Stop to halt immediately. Iterations already running finish, so the body must be safe to execute after the request to stop.
  7. Writing to adjacent array slots from different partitions. False sharing makes correct, lock-free code slower than sequential. Accumulate locally and write once.
  8. Leaving MaxDegreeOfParallelism unbounded inside a request handler. One report can then consume every core. Cap it for background work running alongside live traffic.

Best Practices

  • Confirm the items are genuinely independent before choosing any parallel API; if iteration N reads iteration N-1's output, the answer is a different algorithm.
  • Prefer the partition-local pattern — seed a local, accumulate without synchronisation, merge once — for every aggregate.
  • Benchmark sequential against parallel with a realistic input size, and keep whichever wins.
  • Sort parallel results with a total ordering whenever the output is compared, asserted, or shown to a person.
  • Set MaxDegreeOfParallelism explicitly for anything that shares a machine with user-facing work.
  • Pass a CancellationToken through ParallelOptions so long batches can be shut down cleanly.
  • Reach for Parallel.ForEachAsync for concurrent I/O and keep Parallel.For/PLINQ for CPU-bound work.
  • Use the Concurrent* collections rather than adding your own lock around a List or Dictionary.

Practice Exercises

  1. Time three implementations of sum of n%7 for n up to ten million: a plain for, Parallel.For with a shared Interlocked.Add per iteration, and Parallel.For with localInit/localFinally. Report all three timings and explain the middle one.
  2. Take the word-count example, remove the per-document local Dictionary, and update counts directly per occurrence. Verify the totals still match, then measure both versions on a corpus of a few thousand documents and quantify the contention.
  3. Write a parallel search over a large array that returns the lowest index matching a predicate. Use ParallelLoopState.Break and ParallelLoopResult.LowestBreakIteration, and prove with a test that it never returns a higher index than the sequential version.
  4. Convert a batch of ten HTTP requests from Parallel.ForEach with .Result to Parallel.ForEachAsync with a degree of 3. Log the start and finish time of each request and explain from the log why the second version never has more than three in flight.