Catalog My learning Blog
Full-Stack Developer Course: React, .NET and SQL Server · Phase 12 · Lesson 112 · 7 min read

.NET Concurrency: Channels, SemaphoreSlim, Parallel

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: A Bounded Pipeline, Throttled Calls and an Atomic Redemption
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Distinguish asynchronous from parallel work, build a bounded producer and consumer pipeline with channels, throttle concurrent calls, recognize check-then-act race conditions in business logic, and fix them with atomic database operations instead of locks.

Concept Explanation

Day 6 introduced async and await as a way to avoid blocking threads while waiting for input and output. Concurrency is a broader topic: many things happening at once, whether that is many requests, background workers, or parallel computations. Two ideas need to be kept apart. Asynchronous code frees a thread while waiting for something slow, such as the network, and it is what you want for calls to databases and APIs. Parallel code uses multiple threads at once to speed up CPU-bound work, such as image processing, and it helps only when there is real computation to spread. Starting a hundred parallel tasks that each make a network call, without limits, does not make anything faster and can exhaust connections, sockets, or the downstream service, so concurrency must be bounded.

System.Threading.Channels is the modern building block for pipelines. A channel is a thread-safe queue with asynchronous read and write operations. A bounded channel has a capacity, and when it is full, producers wait, which is called backpressure and is what prevents a fast producer from filling memory when the consumer is slower. It fits the background work of Day 65 well. SemaphoreSlim limits how many operations run at a time, for example five calls to a payment provider at once, and Parallel.ForEachAsync runs an asynchronous body with a maximum degree of parallelism. Two hazards are worth memorizing. A lock statement cannot contain an await, so use SemaphoreSlim for async mutual exclusion, and blocking on a task with .Result or .Wait() in request code can starve the thread pool and stall the whole service, which is why async code should be async all the way up.

The concurrency bugs that matter most for a business application are not low-level data races but check-then-act races on shared state. Code reads a value, decides, and writes, and two requests interleave between the read and the write. A coupon limited to one hundred uses is redeemed one hundred and five times, an account is withdrawn from twice, or two users book the last seat. Locks in application code do not solve this in a system with more than one server instance, since each instance has its own memory. The reliable fixes are in the database: a single atomic statement such as an UPDATE with a condition in the WHERE clause and checking the number of rows affected, a unique constraint that makes duplicates impossible, optimistic concurrency with a version column as in Day 37, or a serializable transaction where that is really needed.

These races are security issues as well as correctness issues, since attackers deliberately send simultaneous requests to exploit them, a technique called a race condition attack, or a limit overrun. Any rule that says at most once or at most N times, including one-time tokens, password reset links, rate limits, and single-use invitations, must be enforced atomically. Also protect shared in-memory state: ConcurrentDictionary is thread safe, but its GetOrAdd factory can run more than once, so side effects inside it are dangerous, and a singleton that keeps per-user data in a field is both a race condition and a data leak between users.

SituationToolNotes
Waiting on I/Oasync and awaitFrees the thread, no extra threads needed
CPU-bound computationParallel.For or Task.RunOnly helps with real computation
Producer faster than consumerBounded ChannelBackpressure prevents unbounded memory
Limit calls to a dependencySemaphoreSlim or Parallel.ForEachAsync with a limitProtects the downstream service
Mutual exclusion in async codeSemaphoreSlim, never lock with awaitlock cannot span an await
At most N uses or single useAtomic conditional UPDATE or unique constraintWorks across server instances

Worked Example: A Bounded Pipeline, Throttled Calls and an Atomic Redemption

The pipeline processes uploads with backpressure. The last block shows the racy coupon code and the atomic fix.

C#
// A bounded channel: if workers fall behind, producers wait instead of exhausting memory.
public sealed class ImportPipeline : BackgroundService
{
    private readonly Channel<ImportJob> _channel = Channel.CreateBounded<ImportJob>(
        new BoundedChannelOptions(capacity: 100) { FullMode = BoundedChannelFullMode.Wait, SingleReader = false });
    private readonly IServiceScopeFactory _scopes;
    private readonly ILogger<ImportPipeline> _log;
    public ImportPipeline(IServiceScopeFactory scopes, ILogger<ImportPipeline> log) { _scopes = scopes; _log = log; }

    public ValueTask EnqueueAsync(ImportJob job, CancellationToken ct) => _channel.Writer.WriteAsync(job, ct);   // waits when full

    protected override async Task ExecuteAsync(CancellationToken stop)
    {
        var workers = Enumerable.Range(0, 4).Select(_ => Task.Run(async () =>
        {
            await foreach (var job in _channel.Reader.ReadAllAsync(stop))
            {
                try { using var scope = _scopes.CreateScope(); await scope.ServiceProvider.GetRequiredService<ImportHandler>().RunAsync(job, stop); }
                catch (Exception ex) when (ex is not OperationCanceledException) { _log.LogError(ex, "Import {JobId} failed", job.Id); }
            }
        }, stop));
        await Task.WhenAll(workers);
    }
}

// Throttle calls to an external provider: at most five in flight, however many requests arrive.
var gate = new SemaphoreSlim(5);
async Task<Quote> GetQuoteAsync(string sku, CancellationToken ct)
{
    await gate.WaitAsync(ct);
    try { return await _http.GetFromJsonAsync<Quote>($"quotes/{Uri.EscapeDataString(sku)}", ct) ?? throw new InvalidOperationException(); }
    finally { gate.Release(); }
}

// Bounded parallelism over a collection.
await Parallel.ForEachAsync(skus, new ParallelOptions { MaxDegreeOfParallelism = 5, CancellationToken = ct },
    async (sku, token) => results[sku] = await GetQuoteAsync(sku, token));
SQL
// RACY: two requests can both read Uses = 99 and both succeed. A C# lock would not help with two server instances.
var coupon = await db.Coupons.SingleAsync(c => c.Code == code, ct);
if (coupon.Uses >= coupon.MaxUses) return Results.Conflict("Coupon exhausted");
coupon.Uses++;
await db.SaveChangesAsync(ct);

// ATOMIC: the database checks and updates in one statement. The rows-affected count is the answer.
var claimed = await db.Coupons
    .Where(c => c.Code == code && c.Uses < c.MaxUses && c.ExpiresAt > DateTimeOffset.UtcNow)
    .ExecuteUpdateAsync(s => s.SetProperty(c => c.Uses, c => c.Uses + 1), ct);
if (claimed == 0) return Results.Conflict("Coupon exhausted or expired");

// Single-use per customer: a unique index makes the duplicate impossible, whatever the timing.
// CREATE UNIQUE INDEX UX_Redemption_Coupon_User ON CouponRedemptions (CouponId, UserId);
try { db.CouponRedemptions.Add(new CouponRedemption(couponId, userId)); await db.SaveChangesAsync(ct); }
catch (DbUpdateException ex) when (ex.IsUniqueViolation()) { return Results.Conflict("Already redeemed"); }
JavaScript
// Test the race directly: fire many concurrent requests at the endpoint and assert the invariant.
var results = await Task.WhenAll(Enumerable.Range(0, 200).Select(_ => client.PostAsync("/api/coupons/SAVE10/redeem", null)));
Assert.Equal(coupon.MaxUses, results.Count(r => r.IsSuccessStatusCode));       // exactly the limit, never more

The final test is the important habit: race conditions rarely show up in ordinary tests, so any rule of the form at most N should have a test that hammers it concurrently.

A bounded channel applies backpressure, semaphores and maximum parallelism protect dependencies, and check-then-act rules must be enforced atomically in the database because locks in one process cannot coordinate several server instances.
A bounded channel applies backpressure, semaphores and maximum parallelism protect dependencies, and check-then-act rules must be enforced atomically in the database because locks in one process cannot coordinate several server instances.

Real-World Examples

  • In 2015 the security researcher Egor Homakov reported a race condition in Starbucks gift card handling, where simultaneous transfer requests could create balance from nothing, and he was able to demonstrate it with only a few dollars. It is a classic example of a business rule, that a balance cannot be spent twice, failing because the check and the update were not atomic.
  • The Dirty COW vulnerability, CVE-2016-5195, was a race condition in the Linux kernel's copy-on-write handling that allowed local privilege escalation and had existed for about nine years before it was found in 2016. It shows that races are not only a business logic issue and that attackers actively look for timing windows.
Key TakeawaysUse async for waiting and parallelism only for computation, and always bound concurrency with channels, semaphores, or maximum parallelism. Enforce at most N and single-use rules with atomic conditional updates or unique constraints in the database, since locks do not work across instances, and write concurrent tests for those rules.

Review Questions & Answers

When the channel is full, writers wait, which applies backpressure to fast producers instead of letting the queue grow until memory is exhausted. The system slows down gracefully under load instead of failing.

A lock only coordinates threads inside one process, and each server instance has its own memory, so two instances can both pass the check. The rule has to be enforced in the shared database, using an atomic conditional update or a unique constraint.

It blocks a thread pool thread while waiting, and under load many blocked threads can starve the pool so that continuations cannot run, causing the service to stall or deadlock. Async should be used all the way up the call chain.

They send many identical requests at the same instant so that several pass the check before any performs the update, exceeding a limit or spending a balance twice. Atomic database operations make only the permitted number of requests succeed, regardless of timing.