I inherited a .NET project whose cloud bill looked far too high for the traffic it served. The cause turned out to be a small piece of code that kept the CPU busy around the clock, and the fix was a SemaphoreSlim . This article walks through what was happening, what a semaphore actually is, and why it was the right tool. I can't share the original code, so the examples are a faithful reconstruction of the pattern rather than the project itself.
The symptom: a CPU that never rests
The app had a background worker that processed jobs (think emails, orders or report requests) added to an in-memory queue by other parts of the application. The worker looked roughly like this:
public class JobWorker : BackgroundService { private readonly ConcurrentQueue < Job > _queue ;
protected override async Task ExecuteAsync ( CancellationToken ct ) { while ( ! ct . IsCancellationRequested ) { if ( _queue . TryDequeue ( out var job ) ) { await Process ( job ) ; } // queue empty? Loop immediately and check again.…