SkillPilotAI

Threads, locks and parallel code

When several threads change the same data at the same time, you get race conditions: bugs that give a different result on every run. This video shows how to make shared state safe with lock, Interlocked and SemaphoreSlim, which thread-safe collections to use, and how to run work in parallel with Parallel.ForEachAsync and PLINQ.

35.1 Why is it used?

  • Servers run many requests at once and background workers share counters, caches and queues.
  • Without synchronization shared updates get lost and normal collections can even throw.
  • Parallel processing uses all CPU cores for heavy work and limits how many external calls run at once.
  • Demo: 4 workers x 100,000 increments should give 400000, but runs gave 303752 and 233028.

35.2 The bug: a race condition

C#
int orders = 0; var workers = Enumerable.Range(0, 4)    .Select(_ => Task.Run(() =>    {        for (int i = 0; i < 100_000; i++)            orders++;    })); await Task.WhenAll(workers);Console.WriteLine($"Orders: {orders}");
Output
$ dotnet run Race.csOrders: 303752$ dotnet run Race.csOrders: 233028
How an order gets lost
  1. 1.orders++ is three steps: read, add, write

  2. 2.Thread A reads 100, thread B reads 100

  3. 3.Both add 1: 101

  4. 4.Both write 101: one increment lost

  5. 5.Result depends on timing: different every run

Race condition: only one thread may run this at a time

35.3 Fix 1: lock

  • lock (gate) lets only one thread at a time into the block; others wait outside.
  • Lock gate = new() uses the new System.Threading.Lock type from C# 13 (any reference object works in older code).
  • Use lock when an update of several lines must happen together. Result: exactly 400000.
C#
int orders = 0;Lock gate = new(); var workers = Enumerable.Range(0, 4)    .Select(_ => Task.Run(() =>    {        for (int i = 0; i < 100_000; i++)            lock (gate)            {                orders++;            }    })); await Task.WhenAll(workers);Console.WriteLine($"Orders: {orders}");
Output
$ dotnet run LockFix.csOrders: 400000

35.4 Fix 2: Interlocked

  • Interlocked.Increment(ref orders) increments with one atomic CPU instruction.
  • Lighter than lock; the fastest choice for counters and simple flags (also Add, Exchange, CompareExchange).
C#
int orders = 0; var workers = Enumerable.Range(0, 4)    .Select(_ => Task.Run(() =>    {        for (int i = 0; i < 100_000; i++)            Interlocked.Increment(ref orders);    })); await Task.WhenAll(workers);Console.WriteLine($"Orders: {orders}");
Output
$ dotnet run InterlockedFix.csOrders: 400000

35.5 Checkpoint: await inside a lock?

  • Compile error CS1996: after an await the method can continue on a different thread.
  • A lock must be released by the thread that took it, so the compiler blocks it upfront.
  • Async code needs a different tool: SemaphoreSlim.
C#
Lock gate = new();int stock = 10; lock (gate){    await Task.Delay(100); // save to DB    stock--;}Console.WriteLine(stock);
Output
$ dotnet run LockAwait.csLockAwait.cs(6,5): error CS1996: Cannot await  in the body of a lock statementThe build failed. Fix the build errors and run again.

35.6 SemaphoreSlim: async throttling

  • SemaphoreSlim(3) is a gate with 3 slots and works with await.
  • WaitAsync waits for a slot without blocking a thread.
  • Release in finally always gives the slot back, even on an exception.
  • Output: SMS 1-3 go at 0.0 s, SMS 4-6 at 0.5 s (order within a batch may vary).
C#
using System.Diagnostics;var gate = new SemaphoreSlim(3);var clock = Stopwatch.StartNew();var sms = Enumerable.Range(1, 6).Select(async i =>{    await gate.WaitAsync();    try    {        var t = clock.Elapsed.TotalSeconds;        Console.WriteLine($"SMS {i} at {t:0.0}s");        await Task.Delay(500);    }    finally { gate.Release(); }});await Task.WhenAll(sms);
Output
$ dotnet run Throttle.csSMS 1 at 0.0sSMS 2 at 0.0sSMS 3 at 0.0sSMS 4 at 0.5sSMS 6 at 0.5sSMS 5 at 0.5s

35.7 Thread-safe collections

  • A normal Dictionary updated from many threads loses updates (253511 instead of 300000) and may throw.
  • ConcurrentDictionary.AddOrUpdate adds or updates a key safely: always 300000.
  • Frozen collections (ToFrozenDictionary) are read-only and optimized for lookups; any number of threads can read without a lock.
  • Immutable collections never change: Add returns a new collection (cart 1 vs cart2 2).
C#
var views = new Dictionary<string, int>();string[] products = ["phone", "tv", "fan"]; Parallel.For(0, 300_000, i =>{    var p = products[i % 3];    views[p] = views.GetValueOrDefault(p) + 1;});Console.WriteLine(views.Values.Sum());// 253511 (differs every run, may throw)
C#
using System.Collections.Concurrent;var views =    new ConcurrentDictionary<string, int>();string[] products = ["phone", "tv", "fan"]; Parallel.For(0, 300_000, i =>{    var p = products[i % 3];    views.AddOrUpdate(p, 1, (_, old) => old + 1);});Console.WriteLine(views.Values.Sum());// 300000
C#
using System.Collections.Frozen;using System.Collections.Immutable; var gst = new Dictionary<string, decimal>{    ["food"] = 0.05m,    ["phone"] = 0.18m}.ToFrozenDictionary();Console.WriteLine(gst["phone"]); var cart = ImmutableList.Create("phone");var cart2 = cart.Add("charger");Console.WriteLine($"{cart.Count} vs {cart2.Count}");
Output
$ dotnet run FrozenImmutable.cs0.181 vs 2

35.8 Channel: producer / consumer queue

  • Channel.CreateBounded<int>(100) is a thread-safe queue holding at most 100 items; the writer waits when it is full (back-pressure).
  • Producer: Writer.WriteAsync; consumer: await foreach over Reader.ReadAllAsync().
  • Writer.Complete() ends the consumer's loop.
C#
using System.Threading.Channels; var queue = Channel.CreateBounded<int>(100); var packer = Task.Run(async () =>{    var orders = queue.Reader.ReadAllAsync();    await foreach (var id in orders)        Console.WriteLine($"Packed order {id}");}); for (int id = 101; id <= 103; id++)    await queue.Writer.WriteAsync(id);queue.Writer.Complete();await packer;
Output
$ dotnet run ChannelQueue.csPacked order 101Packed order 102Packed order 103
Producer / consumer with a Channel
  1. 1.Orders arrive: Writer.WriteAsync(id)

  2. 2.Bounded channel buffers up to 100 items

  3. 3.Full? the writer waits (back-pressure)

  4. 4.Packer task: await foreach over ReadAllAsync

  5. 5.Writer.Complete(): the packer loop ends

Hand off work between threads without locks

35.9 Parallel.ForEachAsync and PLINQ

  • Parallel.ForEachAsync processes items concurrently and supports async work.
  • MaxDegreeOfParallelism = 3 caps it at 3 API calls at a time: 6 calls take 1.2 s instead of ~3 s.
  • PLINQ: add AsParallel() to a LINQ query to split CPU work across all cores.
  • On an 8-core machine LINQ took 2968 ms and PLINQ 1047 ms; timings vary, and for small work PLINQ can be slower.
C#
using System.Diagnostics; int[] orderIds = [101, 102, 103, 104, 105, 106];var options = new ParallelOptions{    MaxDegreeOfParallelism = 3};var clock = Stopwatch.StartNew();await Parallel.ForEachAsync(orderIds, options,    async (id, ct) =>    {        await Task.Delay(500, ct); // API call    });var secs = clock.Elapsed.TotalSeconds;Console.WriteLine($"Done in {secs:0.0}s");
Output
$ dotnet run ParallelAsync.csDone in 1.2s
C#
var numbers = Enumerable.Range(1, 3_000_000);Time("LINQ", () => numbers.Count(IsPrime));Time("PLINQ",    () => numbers.AsParallel().Count(IsPrime)); static void Time(string name, Func<int> count){    long start = Environment.TickCount64;    int n = count();    long ms = Environment.TickCount64 - start;    Console.WriteLine($"{name}: {n}, {ms} ms");}static bool IsPrime(int n) => n > 1 && Enumerable    .Range(2, (int)Math.Sqrt(n) - 1)    .All(d => n % d != 0);
Output
$ dotnet run Plinq.csLINQ: 216816, 2968 msPLINQ: 216816, 1047 ms

35.10 When to use which

NeedToolNote
Update one numberInterlockedAtomic, fastest
Multi-line shared update (sync code)lockKeep it short, no await inside
Limit concurrent async callsSemaphoreSlimWaitAsync + Release in finally
Shared dictionaryConcurrentDictionaryAddOrUpdate / GetOrAdd
Read-only shared dataFrozen / ImmutableNo lock needed
Hand work between threadsChannelBounded = back-pressure
Many async callsParallel.ForEachAsyncSet MaxDegreeOfParallelism
Heavy CPU workPLINQ (AsParallel)Measure first
Which tool when?
  1. 1.Shared number or state: Interlocked / lock

  2. 2.Async code needs a limit: SemaphoreSlim

  3. 3.Sharing data: Concurrent collections / Channel

  4. 4.Read-only data: Frozen, no lock at all

  5. 5.Lots of work: PLINQ (CPU) / ForEachAsync (async)

35.11 Common mistakes

  • Updating a normal Dictionary or List from several threads.
  • await inside lock (compile error) or blocking waits instead of SemaphoreSlim.
  • Forgetting Release in finally: slots leak and everything eventually waits forever.
  • Myth: more threads = more speed. Cores are limited and switching costs; use Task and the thread pool, not new Thread.
  • Myth: ConcurrentDictionary makes everything safe. ContainsKey followed by Add is still two separate steps, not atomic.

35.12 Interview tips

  • Race condition: several threads change shared data without synchronization and the result depends on timing.
  • Interlocked for counters, lock for multi-step updates, SemaphoreSlim in async code (you cannot await inside lock).
  • ConcurrentDictionary or Channel for shared collections, Frozen collections for read-only data.
  • Parallel.ForEachAsync with MaxDegreeOfParallelism for async calls, PLINQ for CPU work, after measuring.