Introduction
Picture the front gate of a large company — a century-old corporation with dozens of sites and 80,000 active employees on record. It is 8 a.m. on a Monday: hundreds of people arrive at the same time, each one tapping their badge on the electronic turnstiles. For each badge, the system must perform a validation against the corporate database: fetch the record, check the status, verify access permissions and log the entry.
If this system is sequential — processing one validation at a time, in a queue — people will pile up at the entrance. With 80,000 records and a lookup time of a few milliseconds per query, the math is cruel. This is where parallelism comes in.
Unlike asynchronous programming — which is about releasing the thread while waiting for I/O (read more in Asynchronous Programming in C#: async/await and Threads) — parallelism is about using multiple CPU cores simultaneously to process tasks at the same time. It is the right strategy when the bottleneck is processing rather than waiting for I/O.
In this article you will understand what parallelism is, how it works in .NET, which tools to use (Parallel.ForEach, PLINQ, Task.Run), how to avoid the classic concurrency pitfalls and, above all, when each approach makes sense — all anchored in the corporate turnstile example.
📦 Source code: The complete implementation for this article is in the blog-zocateli-sample repository on GitHub. Clone it, explore it and adapt it to your context.
Prerequisites
- Familiarity with C# and .NET (6+)
- Basic understanding of threads and
Task - Recommended: reading the article on asynchronous programming in C#
The Problem: The Corporate Turnstile
Before writing a single line of code, I want to understand the concrete problem.
The company TechCorp Centenária S.A. has:
- 80,000 employees active across 12 sites
- A legacy corporate database with access control records
- 200 turnstiles spread across the entrances of every building
- Access peak: 2,000 employees showing up in the first 15 minutes of the shift
The current system is simple: when the badge is read, a sequential search is performed over an in-memory list loaded from the database. The original code is this:
| |
With 80,000 records and 2,000 validations arriving almost simultaneously, the foreach loop processes one at a time. This is a CPU-bound problem: the processor is working, not waiting — but it is working alone, on a single core.
💡 Tip: Tell the problems apart before choosing the solution. Ask yourself: “is my process waiting for data (I/O-bound) or processing data (CPU-bound)?” For I/O-bound, use async/await. For CPU-bound, use parallelism.
Asynchronous vs Parallel: the Difference That Changes Everything
It is essential to be clear about this distinction before moving on:
| Asynchronous Programming | Parallelism | |
|---|---|---|
| Solves | Waiting bottlenecks (I/O) | Processing bottlenecks (CPU) |
| How | Releases the thread while waiting | Uses multiple threads simultaneously |
| Tool | async/await, Task | Parallel, PLINQ, Task.Run |
| Example | Database query | Processing 80k records in memory |
| Cores used | Efficient with 1 core | Uses all available cores |
In the turnstile problem:
- Querying the database to load the records → asynchronous (
ToListAsync()) - Processing/validating the 80,000 records in memory → parallel (
Parallel.ForEach)
Many real solutions combine both patterns, and you will see that throughout this article.
How Parallelism Works in .NET
.NET manages threads through the ThreadPool — a set of pre-allocated threads ready for use. When you use Parallel.ForEach or Task.Run, the runtime distributes the work among the threads available in the pool, mapping them to the physical CPU cores.
Automatic Partitioning
The biggest strength of Parallel in .NET is automatic partitioning: the runtime splits the collection into blocks (chunks) and hands each block to a different thread. This avoids the overhead of creating one thread per item.
| |
On an 8-core machine, 80,000 records would be split into ~8 partitions of 10,000, reducing processing time by up to 8x (in practice a bit less due to synchronization overhead).
Parallel.ForEach — The Solution for the Turnstile
The most direct tool to parallelize a foreach is Parallel.ForEach. Here is how to transform the sequential code:
| |
⚠️ Warning: Note the use of
ConcurrentBag<T>instead ofList<T>. A regularList<T>is not thread-safe — multiple threads adding items simultaneously would cause data corruption or exceptions. Always use collections from theSystem.Collections.Concurrentnamespace in parallel scenarios.
Controlling the Degree of Parallelism
By default, .NET uses all available cores. In production, that can be too aggressive — you may want to cap it so you do not saturate the server and impact other processes:
| |
💡 Tip: A good starting point for
MaxDegreeOfParallelismisEnvironment.ProcessorCount(the number of logical cores on the machine) orEnvironment.ProcessorCount / 2to leave room for other processes.
Speeding Up the Lookup: The Right Data Structures
Before parallelizing, check whether the data structure is the bottleneck. In the turnstile example, FirstOrDefault on a List<T> has O(n) complexity — it walks the whole list until it finds the item. With 80,000 records, that is expensive.
The solution is to pre-index the data in a Dictionary<string, RegistroFuncionario>:
| |
ℹ️ Info:
Dictionary<TKey, TValue>is not thread-safe for writes, but it is safe for concurrent reads when the dictionary is not being modified. Since the index is built once and only read in parallel, this pattern is correct. If you need concurrent writes, useConcurrentDictionary<TKey, TValue>.
PLINQ: Parallelism with the Elegance of LINQ
PLINQ (Parallel LINQ) is a parallel version of traditional LINQ. Just add .AsParallel() to any LINQ query and the runtime automatically distributes processing across threads.
| |
PLINQ with Ordering
An important point: PLINQ does not guarantee result order by default. If order matters (e.g. generating a report in arrival order), use .AsOrdered():
| |
⚠️ Warning:
.AsOrdered()has an additional synchronization cost — threads need to coordinate the order of the results. Use it only when really necessary.
Parallel.ForEachAsync — Combining Parallel and Asynchronous
The real turnstile scenario is richer: validation involves both in-memory processing and database queries. For that, .NET 6+ offers Parallel.ForEachAsync — which combines CPU parallelism with asynchronous I/O operations:
| |
This is the most powerful pattern: it does not block threads during I/O (asynchronous) and uses multiple cores for processing (parallel).
ConcurrentDictionary: Shared State without Manual Locks
Besides ConcurrentBag, ConcurrentDictionary<TKey, TValue> is one of the most useful structures in parallel scenarios. Imagine the turnstile needs to accumulate access statistics per site:
| |
💡 Tip:
ConcurrentDictionaryis far more efficient than aDictionarywith a manuallockin high read/write concurrency scenarios, because it uses lock striping internally — splitting the dictionary into independent segments to minimize contention.
Controlling Access to Limited Resources with SemaphoreSlim
In real life, turnstiles have physical limits — you cannot let 100 people through the same gate at once. The same applies to code: when you have a limited shared resource (database connections, external APIs, files), use SemaphoreSlim to control concurrent access:
| |
The metaphor is accurate: SemaphoreSlim is literally a traffic light — it controls how many simultaneous “passages” are allowed. WaitAsync waits for a slot; Release frees one.
Thread Safety: Classic Pitfalls in Parallelism
When parallelizing code, the most common bugs are race conditions — situations where the result depends on the unpredictable order in which threads execute. Here are the most frequent cases:
Shared Counters
| |
Lists as Accumulators
| |
Accessing External Resources (Databases, Files)
| |
ℹ️ Info: Entity Framework Core’s
DbContextwas designed to be scoped (one per request). Never share a singleDbContextacross threads — that causes concurrency exceptions and incorrect results. In parallel code, create oneDbContextper iteration usingIServiceScopeFactory.
Parallel.For vs Parallel.ForEach vs PLINQ
Which one to use in each situation?
| Scenario | Recommendation |
|---|---|
| Iterate a collection with an index | Parallel.For(0, n, i => ...) |
| Iterate a collection of objects | Parallel.ForEach(colecao, item => ...) |
| Transform a collection (projection) | colecao.AsParallel().Select(...) |
| Filter and transform | colecao.AsParallel().Where(...).Select(...) |
| Requires async I/O + parallelism | Parallel.ForEachAsync(colecao, async (item, ct) => ...) |
| Control limited resources | SemaphoreSlim + Task.WhenAll |
| |
Complete Example: Turnstile System in Production
Now I will put together the complete scenario with every pattern covered — from asynchronous loading from the database to parallel validation and the final report:
| |
When NOT to Use Parallelism
Parallelism is not a silver bullet. There are situations where it worsens performance:
1. Small collections: The overhead of creating and synchronizing threads can outweigh the benefit. For fewer than ~1,000 simple items, sequential code is usually faster.
2. Simple I/O-bound operations: If the bottleneck is the network or disk, adding threads does not help — the bottleneck remains external. Use async/await.
3. Operations that cannot be made thread-safe: If processing each item depends on the result of the previous ones (mandatory shared state), parallelism adds complexity without benefit.
4. Legacy code with hidden side effects: Global variables, singletons with mutable state, non-thread-safe logging — parallelizing code like this produces bugs that are hard to reproduce.
| |
Measuring the Difference: Benchmark
To feel the difference in practice, here is a simple benchmark using System.Diagnostics.Stopwatch:
| |
💡 Tip: For serious benchmarks, use the BenchmarkDotNet library — it controls variables such as JIT warm-up, GC and statistical variance, producing far more reliable results.
Summary: When to Use Each Tool
| Tool | Best For | Avoid When |
|---|---|---|
Parallel.For | Indexed arrays, large volume, CPU-bound | Small collections |
Parallel.ForEach | Object collections, CPU-bound | Pure I/O operations |
PLINQ (.AsParallel()) | Transformation/filter pipelines | When order matters (cost) |
Parallel.ForEachAsync | CPU + I/O (async inside parallel) | Simple pure CPU |
Task.WhenAll + SemaphoreSlim | Controlling the rate of concurrent I/O | Heavy CPU-bound |
ConcurrentDictionary | Shared state with many writes | Read-only (use Dictionary) |
Interlocked | Atomic counters and flags | Complex structures |
Conclusion
The corporate turnstile example is perfect to illustrate when and why parallelism matters. A century-old company cannot have employees waiting in line because the system processes one badge at a time. With Parallel.ForEach, PLINQ and .NET’s concurrent collections, you can turn processes that took hundreds of milliseconds into tens — or less.
The key points to remember:
- Parallelism is for CPU-bound work — when the processor is working, not waiting
- Combine it with async/await for scenarios involving I/O
- Always use thread-safe collections (
ConcurrentBag,ConcurrentDictionary) to accumulate results - Control the degree of parallelism with
MaxDegreeOfParallelism— “maximum” is not always “better” - Use
SemaphoreSlimto protect limited resources (connections, external APIs) - Measure before and after — poorly applied parallelism can be slower than sequential code
💡 Final Tip: C# and the .NET ecosystem offer one of the most complete and well-documented parallelism implementations on the market. The TPL (Task Parallel Library), PLINQ and the concurrent collections are part of the standard runtime — no external dependencies, no extra configuration. If you are building systems that need to scale, C# is an excellent choice thanks to its maturity in this area. To go deeper, also explore Channels and System.Threading.Tasks.Dataflow for high-performance pipelines.
Read Also
- Asynchronous Programming in C#: async/await and Threads
- Database Bottlenecks: Messaging and Pagination
- REST API Pagination with C# and EF Core: Practical Guide
- .NET Worker and Background Service: High Volume
References
- Task Parallel Library (TPL) — Microsoft Docs
- Parallel LINQ (PLINQ) — Microsoft Docs
- System.Collections.Concurrent — Microsoft Docs
- Parallel.ForEachAsync — .NET 6+ — Microsoft Docs
- BenchmarkDotNet — Benchmarking Library for .NET
- Asynchronous Programming in C# — zocate.li
- blog-zocateli-sample repository — AsyncParallel — Complete source code for the examples in this article

By commenting, you agree to our Privacy Policy, Terms of Use, Data Deletion Policy.