Volume 1 · Chapter 6 — Modern C# and .NET Foundations

Threading and Concurrency

Goutham Mayaluri 9 min read .NETC#Threading

6.1 Introduction

Concurrency is an application’s ability to make progress on multiple operations during overlapping time periods. Enterprise systems rely on it to handle thousands of requests, messages, and background jobs efficiently. But concurrency is where the subtlest, most damaging bugs live: incorrect synchronization causes race conditions, deadlocks, and data corruption that are hard to reproduce and diagnose. The core skill is protecting shared mutable state correctly - and, better still, minimizing shared mutable state in the first place.

6.2 Threads vs Tasks vs the Thread Pool

A thread is a low-level OS execution unit that consumes significant resources (~1 MB stack) and must be managed manually. ATaskis a higher-level abstraction over asynchronous or parallel work, scheduled efficiently on the thread pool. The thread pool maintains reusable worker threads so applications avoid the cost of creating a thread per operation.

flowchart TB
  Req["Work items / requests"] --> Queue["Thread Pool Queue"]
  Queue --> W1["Worker thread"]
  Queue --> W2["Worker thread"]
  Queue --> W3["Worker thread (reused)"]
  W1 --> Done["Execute work, return thread to pool"]

6.3 Parallelism vs Async

Parallelism (the Task Parallel Library,Parallel.For, PLINQ) runs independent work simultaneously across cores - the right tool for CPU-bound workloads. Async is for I/O-bound work. Confusing them is a common mistake: wrapping I/O inParallel.FororTask.Runjust wastes threads, while running CPU-bound work inline blocks the caller.


// CPU-bound: parallelism across cores is appropriate.
Parallel.For(0, items.Length, i => Compute(items[i]));

// I/O-bound with bounded concurrency: don't fan out unbounded.
await Parallel.ForEachAsync(ids,
    new ParallelOptions { MaxDegreeOfParallelism = 8 },
    async (id, ct) => await _client.FetchAsync(id, ct));

6.4 Synchronization Primitives

When threads must share mutable state, you synchronize access.lock(Monitor) gives mutual exclusion so only one thread enters a critical section;SemaphoreSlimlimits concurrency to N (and has an async-friendlyWaitAsync); and concurrent collections provide thread-safe data structures without manual locking.


private readonly object _gate = new();
void UpdateBalance(decimal delta)
{
    lock (_gate) { _balance += delta; }   // mutual exclusion - one thread at a time
}

// Limit concurrent downstream calls to protect a dependency.
private readonly SemaphoreSlim _limit = new(8);
async Task CallAsync(CancellationToken ct)
{
    await _limit.WaitAsync(ct);
    try { await _dependency.InvokeAsync(ct); }
    finally { _limit.Release(); }
}

Thread-safe collections -ConcurrentDictionary,ConcurrentQueue,ConcurrentStack,BlockingCollection- handle concurrent access correctly without you writing lock code.

6.5 Race Conditions and Deadlocks

Arace conditionoccurs when the result depends on the timing of concurrent access to shared data - for example two threads both reading a value, both incrementing it, and one overwriting the other’s update. Adeadlockoccurs when threads wait permanently for resources each other holds. Both are prevented by design: minimize shared mutable state, acquire locks in a consistent order, keep lock scopes small, and use timeouts.

sequenceDiagram
  autonumber
  participant A as Thread A
  participant B as Thread B
  participant R1 as Resource 1
  participant R2 as Resource 2
  A->>R1: lock
  B->>R2: lock
  A->>R2: wait for lock (held by B)
  B->>R1: wait for lock (held by A)
  Note over A,B: Neither can proceed -> DEADLOCK
Senior Interview Question

When should you use Parallel.For instead of async/await?

I useParallel.For(and the TPL/PLINQ) for CPU-bound work that can be split across cores - computations where the goal is to use multiple processors to finish faster, like processing a large in-memory dataset or running independent calculations. I useasync/awaitfor I/O-bound work - database queries, HTTP calls, file and message operations - where the goal is not to use more CPU but to avoid blocking a thread while waiting, so the thread is freed to serve other work. The distinction is fundamental: parallelism is about doing more computation at once (CPU-bound), async is about not wasting threads during waits (I/O-bound). Confusing them causes real problems - wrapping I/O inParallel.FororTask.Runconsumes threads to sit and wait, which wastes the thread pool and can starve it, while running CPU-bound work on the request thread synchronously blocks it. There is also a middle case: overlapping many independent I/O operations, for which I useawait Task.WhenAllorParallel.ForEachAsyncwith a boundedMaxDegreeOfParallelism, combining async I/O with controlled concurrency. So the rule is: CPU-bound and parallelizable →Parallel.For; I/O-bound → async; many concurrent I/O calls → bounded async fan-out.

Senior Interview Question

What is a race condition, and how do you prevent it?

A race condition occurs when two or more threads access shared mutable state concurrently and the correctness of the result depends on the unpredictable timing of their execution. The classic example is a read-modify-write: two threads both read a counter as 10, both increment to 11, and both write 11, so one update is lost and the result is wrong - the outcome “races” on which thread runs when. Race conditions are insidious because they are timing-dependent, often only appear under load, and are hard to reproduce. I prevent them primarily by minimizing shared mutable state - using immutable data, message passing, or per-request/per-thread state so there is nothing to race on - which is the most robust approach. Where shared mutable state is unavoidable, I protect it with synchronization: alockaround the critical section so only one thread performs the read-modify-write at a time, atomic operations (Interlocked) for simple counters, thread-safe concurrent collections, or, for data, database concurrency controls (optimistic concurrency with a version/rowversion, or appropriate isolation). I keep critical sections small and hold locks briefly to limit contention. In a distributed context (multiple instances), in-process locks are not enough, so I use database-level concurrency, idempotency, or distributed coordination. The principle is: prefer designs with no shared mutable state, and where you must share it, serialize access correctly so timing cannot corrupt the result.

Senior Interview Question

What causes a deadlock and how do you prevent it?

A deadlock occurs when two or more threads each hold a resource the other needs and wait for each other indefinitely, so none can proceed - the classic case is thread A locking resource 1 then waiting for resource 2, while thread B has locked resource 2 and waits for resource 1. It requires several conditions together (mutual exclusion, hold-and-wait, no preemption, and a circular wait), and breaking any of them prevents it. The most effective prevention is to impose a consistent global ordering on lock acquisition - always acquire locks in the same order everywhere - which eliminates the circular wait. Beyond that: keep lock scopes as small as possible and avoid holding a lock while calling out to code that might acquire other locks (or do I/O); avoid nested locks where you can; use lock timeouts (Monitor.TryEnterwith a timeout) so a thread gives up rather than waiting forever; and minimize locking altogether by reducing shared mutable state. In async code, deadlocks also arise from sync-over-async (.Result/.Wait()blocking a context needed by a continuation), which is fixed by being async all the way down. So I prevent deadlocks by designing for consistent lock ordering, small lock scopes, timeouts, and minimal shared state, and by never blocking on async. When one does occur, I diagnose it from a thread dump showing the circular wait.

Principal Engineer Question

How do you troubleshoot a concurrency problem in production?

Concurrency bugs are timing-dependent and often intermittent, so I lead with evidence and reproduction rather than guesswork. First I characterize the symptom - is it data corruption/incorrect results (points to a race condition), a hang or stalled throughput (points to a deadlock or lock contention), or collapsing throughput with low CPU (points to thread-pool starvation from sync-over-async)? For a hang or contention, I capture a process dump (dotnet-dump) or thread dump and inspect the threads: a deadlock shows threads blocked in a circular wait on locks; heavy contention shows many threads waiting on the same lock (dotnet-countersalso surfaces lock-contention and thread-pool queue metrics). For starvation, counters show the thread-pool queue climbing and thread count pinned, and the dump shows threads blocked inWaitor synchronous I/O. For data corruption, I look for shared mutable state accessed without synchronization - the code paths that read-modify-write shared data or entities - often correlating with the conditions (peak load) under which it appears. Once I’ve localized it, the fix targets the root cause: add proper synchronization or, better, remove the shared mutable state; enforce consistent lock ordering and small lock scopes to fix deadlocks; make the path fully async to fix starvation; and add idempotency and database concurrency controls where multiple requests or instances update the same entity. I reproduce under load or with stress/concurrency tests to confirm the fix, and add regression tests and analyzers where possible. The discipline is to identify which class of concurrency problem it is from real evidence (dumps, counters), then address the underlying shared-state or ordering issue, rather than sprinkling locks blindly.

6.6 Production Scenario

A payment service produces duplicate transaction updates during peak traffic. Investigation shows multiple concurrent requests updating the same account entity without synchronization - a race condition. The team fixes it not with a naive in-process lock (which would not help across multiple instances) but by designing idempotency (each transaction keyed so a repeat is a no-op), adding optimistic concurrency on the entity (a rowversion so conflicting updates are detected and retried), and ensuring exactly-once message processing - eliminating the duplicates correctly in a distributed setting.

Chapter Revision Notes

  • Threads are heavy OS units; Tasks are pooled, higher-level abstractions.
  • Parallelism is for CPU-bound work; async is for I/O-bound work - don’t confuse them.
  • Protect shared mutable state with locks, semaphores, or concurrent collections - or avoid it.
  • Race conditions come from unsynchronized shared state; prevent by minimizing it.
  • Deadlocks come from circular waits; prevent with consistent lock ordering, small scopes, timeouts.
  • In distributed systems, use idempotency and database concurrency, not just in-process locks.