🔧 C#: Fix a SemaphoreSlim Leak From a Forgotten Release on Throw
A SemaphoreSlim used to guard concurrent access to a limited resource only returns its permit when Release() is actually called — it has no finalizer-based safety net the way some other synchronization primitives do. Code that calls WaitAsync() and then runs work that can throw before reaching its matching Release() call permanently loses that permit, shrinking the effective concurrency limit by one every time it happens, with nothing in the exception itself pointing back to the semaphore at all.
🔎 The Problem
await _semaphore.WaitAsync(); var result = await CallExternalApiAsync(request); // can throw _semaphore.Release(); // never reached if the call above throws return result; // After enough transient failures: semaphore permanently exhausted, // every future WaitAsync() call blocks forever, no exception thrown
✅ Fix: Guarantee the Release With try/finally
- Wrap every
WaitAsync()/Release()pair in atry/finallyblock, callingRelease()unconditionally infinally— this is the one pattern that survives every exit path, including an exception thrown mid-operation. - Log the semaphore’s
CurrentCountperiodically in a health check or diagnostic endpoint during development, so a slow leak shows up as a steadily shrinking number well before it fully exhausts the available permits in production. - Consider wrapping repeated use of the same semaphore in a small helper class that exposes an
IDisposable‘lease’ object acquired viaWaitAsync(), soRelease()happens automatically via ausingblock instead of relying on every call site remembering thetry/finallyby hand.
🚨 Why This Is Dangerous
- Once fully exhausted, a leaked semaphore doesn’t throw or log anything distinctive — every subsequent call simply hangs on
WaitAsync()forever, which looks identical to generic ‘the service is slow’ from the outside and can take hours to correctly diagnose.
A semaphore doesn’t forgive a missed Release — it just quietly has one fewer permit to give out, forever, until the process restarts.



