Skip to content

2.19 — Parallel.For, PLINQ, and When Not to Use Them

← Roadmap · Section: 2. Collections, LINQ and Async Prev: 2.18 Thread safety · Next: 3.1 .NET history

Markers: ⭐ ⚠️ · Confidence: 🔴 · Last reviewed: —


TL;DR

  • Parallel ≠ async. Parallel means "use many CPU cores on one job". Async means "do not block a thread while waiting".
  • Parallel.For and PLINQ are for CPU-bound work over lots of items. They are almost always wrong for I/O.
  • In ASP.NET Core they are usually a mistake, because the server is already busy running other requests in parallel.

The concept

These two words get confused constantly, and the distinction is the point of this note.

Async is about waiting efficiently. Your code asks the network for something and gets on with other work instead of standing idle. It does not make anything faster — it stops threads being wasted.

Parallel is about working faster. You split a computation across CPU cores so it finishes sooner. It genuinely reduces wall-clock time, but only for work that actually uses the CPU.

A picture: one cook waiting for a pot to boil versus four cooks chopping vegetables.

The waiting cook should go and do something else meanwhile — that is async. It does not matter how many cooks you have; the pot boils at its own pace. But chopping a mountain of vegetables genuinely goes four times faster with four cooks — that is parallelism.

Using parallelism for waiting is like hiring four cooks to stand and watch the same pot.


How it works

Parallel.For and Parallel.ForEach

// Sequential — one core
foreach (var image in images)
    Resize(image);

// Parallel — all available cores
Parallel.ForEach(images, image => Resize(image));

The runtime splits the collection across threads and manages the work. For genuinely CPU-heavy work over many items, this scales close to linearly with core count.

Controlling how many run at once:

Parallel.ForEach(
    images,
    new ParallelOptions
    {
        MaxDegreeOfParallelism = 4,
        CancellationToken = ct
    },
    image => Resize(image));

Parallel.ForEachAsync (.NET 6+)

This one is genuinely useful, and it is the exception to "parallel is not for I/O". It runs async operations with a concurrency limit:

await Parallel.ForEachAsync(
    urls,
    new ParallelOptions { MaxDegreeOfParallelism = 10, CancellationToken = ct },
    async (url, token) =>
    {
        var data = await http.GetStringAsync(url, token);
        await SaveAsync(data, token);
    });

This is the clean solution to the throttling problem from 2.12 — instead of SemaphoreSlim wrapped around a WhenAll, you get a built-in concurrency cap. Prefer this for "call a service for each of these 1,000 items, but not all at once".

PLINQ — AsParallel()

// Sequential
var results = numbers.Where(IsPrime).ToList();

// Parallel — one word added
var results = numbers.AsParallel().Where(IsPrime).ToList();

Options:

numbers.AsParallel()
    .WithDegreeOfParallelism(4)
    .WithCancellation(ct)
    .AsOrdered()                    // preserve input order (costs performance)
    .Where(IsPrime)
    .ToList();

⚠️ PLINQ does not preserve order by default. Results come back in whatever order the threads finish. If order matters you need AsOrdered(), which adds buffering and sorting overhead and eats into the benefit.

When parallelism actually pays

There is a fixed cost: partitioning the work, spinning up threads, coordinating, and merging results. That cost has to be smaller than what you save.

// ✓ WORTH IT — expensive work, many items
Parallel.ForEach(images, img => ApplyComplexFilter(img));

// ✗ NOT WORTH IT — trivial work, overhead dominates
Parallel.ForEach(numbers, n => n * 2);       // SLOWER than a plain loop

The rough rule: the per-item work needs to be meaningfully more expensive than the coordination overhead, and there need to be enough items to spread across cores. A hundred items of trivial work will be slower in parallel. A hundred thousand items of real computation will be much faster.

Always measure. BenchmarkDotNet exists for exactly this — 19.14.


⚠️ Why this is usually wrong in ASP.NET Core

This is the part interviewers care about.

A web server is already parallel. It is handling many requests at once, spread across all your cores. Those cores are not sitting idle waiting for you to use them.

When one request calls Parallel.ForEach, it grabs threads from the same shared pool that serves every other request. So:

  • One request gets faster.
  • Every other request gets slower, because the pool is now busier.
  • Under load, requests queue and overall throughput drops.

You have optimised one request at the expense of total capacity. On a server, throughput usually matters more than the latency of any single request.

// In a controller — usually the wrong instinct
[HttpPost("process")]
public IActionResult Process(List<Item> items)
{
    Parallel.ForEach(items, ProcessItem);   // steals threads from other requests
    return Ok();
}

When it is defensible: the work is genuinely CPU-heavy, takes seconds, and the endpoint is low-traffic — a nightly report, an admin-only bulk operation. Even then, MaxDegreeOfParallelism should be capped so it cannot consume every core.

The better answer for heavy work is usually to push it out of the request entirely — onto a background service or a queue — so the request returns immediately and the work happens where it cannot hurt request throughput. See 21.1.

Never use Parallel.ForEach with async lambdas

// BROKEN — this is async void
Parallel.ForEach(urls, async url => await http.GetStringAsync(url));

Parallel.ForEach takes an Action<T>, so an async lambda becomes async void (2.15). The loop returns immediately with all the work still running, unobserved, and any exception crashes the process.

Use Parallel.ForEachAsync or Task.WhenAll instead.


Code

The three ways to handle a batch, and when each is right:

// 1. I/O-bound, all at once — fine for a handful of items
var results = await Task.WhenAll(ids.Select(id => FetchAsync(id, ct)));

// 2. I/O-bound, throttled — the right answer for hundreds or thousands
var results = new ConcurrentBag<Result>();
await Parallel.ForEachAsync(
    ids,
    new ParallelOptions { MaxDegreeOfParallelism = 10, CancellationToken = ct },
    async (id, token) => results.Add(await FetchAsync(id, token)));

// 3. CPU-bound — genuine parallelism across cores
var results = items
    .AsParallel()
    .WithCancellation(ct)
    .Select(ExpensiveTransform)
    .ToList();

Note the ConcurrentBag in the second example. Writing to a plain List<T> from a parallel loop will corrupt it — see 2.3. This is one of the most common bugs in parallel code:

var results = new List<Result>();
Parallel.ForEach(items, item =>
{
    results.Add(Process(item));      // ✗ RACE — List is not thread-safe
});

The failure is nasty because it is intermittent: sometimes you lose items, sometimes you get a corrupted internal array, sometimes it throws IndexOutOfRangeException from inside Add.


Interview questions

Q: What is the difference between parallel and asynchronous?

Async is about not blocking a thread while waiting for something external — a network call or a disk read. It does not make the operation faster; it frees the thread to do other work during the wait. Parallel is about using multiple CPU cores to complete a computation sooner. So async is the answer for I/O-bound work and parallelism is the answer for CPU-bound work. Using parallelism for I/O just occupies several threads all doing nothing, which is strictly worse than one async call.

Q: Why is Parallel.ForEach usually wrong in ASP.NET Core?

Because the server is already parallel — it is handling many requests concurrently across all the cores. Threads come from a shared pool, so when one request parallelises, it takes capacity away from every other request. That makes one request faster and everything else slower, and under load overall throughput drops. On a server, total throughput normally matters more than the latency of an individual request. If the work is genuinely heavy, the better answer is to move it out of the request onto a background service or queue.

Q: When does parallelism actually help?

When the work is CPU-bound, there are enough items to spread across cores, and the per-item cost is significantly larger than the coordination overhead. Partitioning, thread management and merging results all cost something, so parallelising trivial work over a small collection is slower than a plain loop. It also has to be work that can be done independently — if every iteration needs a lock on shared state, you have serialised it again and paid the overhead for nothing. And I would always measure rather than assume.

Q: What is Parallel.ForEachAsync for?

It runs asynchronous operations over a collection with a configurable concurrency limit, which is the missing piece between Task.WhenAll and manual throttling. WhenAll over a thousand items starts a thousand operations at once, which exhausts connections and gets you rate-limited. Before .NET 6 you would wrap a SemaphoreSlim around it; now Parallel.ForEachAsync with MaxDegreeOfParallelism does it cleanly. Despite the name it is about controlled concurrency for I/O, not CPU parallelism.


Traps ⚠️

  • Writing to a List<T> from a parallel loop corrupts it. Use a concurrent collection or collect per-thread results.
  • Parallel.ForEach with an async lambda is async void. Use Parallel.ForEachAsync.
  • PLINQ does not preserve order unless you add AsOrdered(), which costs performance.
  • Parallelism on small or cheap work is slower than sequential, because of coordination overhead.
  • In ASP.NET Core it steals threads from other requests and reduces overall throughput.
  • Exceptions come back wrapped in AggregateException. See 2.16.
  • A lock inside a parallel loop serialises it, so you pay all the overhead and get none of the benefit.
  • Never nest parallel loops. The thread explosion makes it far slower than a single level.


Sources