Menu

Semaphores in .NET: How a Few Lines of Waiting Cut Our Cloud Bill
📰

Semaphores in .NET: How a Few Lines of Waiting Cut Our Cloud Bill

DEV Community: dotnet·Alpha·6 days ago
#YywiHMd7
Long article (1804 words) — no AI summary yet.
Reading 0:00
15s threshold

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.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.