Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio
C#

C#: Fix a SemaphoreSlim Leak From a Forgotten Release on Throw

- 27.11.26 - ErcanOPAK

🔧 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 a try/finally block, calling Release() unconditionally in finally — this is the one pattern that survives every exit path, including an exception thrown mid-operation.
  • Log the semaphore’s CurrentCount periodically 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 via WaitAsync(), so Release() happens automatically via a using block instead of relying on every call site remembering the try/finally by 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.

— C# Best Practice

Related posts:

C# Dependency Injection Containers Slow Startup

C# Dependency Injection Containers Slow Startup

C#: Fix a Task.Delay Call Inside a Retry Loop That Never Actually Delays Because the Returned Task W...

C#: Fix a Task.Delay Call Inside a Retry Loop That Never Actually Delays Because the Returned Task W...

C# — Memory Works with Async, Span Does Not

C# — Memory Works with Async, Span Does Not

Views: 8
Found this useful? Share it
XLinkedInWhatsApp

Post navigation

SQL Server: Fix a Table Variable Breaking a Parallel Query Plan
Windows 11: Fix a Pinned Start Menu Icon Reverting to Generic

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Most Read

  1. 01How to make theater mode the default for Youtube 1,079 views
  2. 02How to add default value for Entity Framework migrations for DateTime and Bool 997 views
  3. 03Get the User Name and Domain Name from an Email Address in SQL 996 views
  4. 04Get the First and Last Word from a String or Sentence in SQL 873 views
  5. 05How to select distinct rows in a datatable in C# 868 views
  6. 06How to enable, disable and check if Service Broker is enabled on a database in SQL Server 671 views
  7. 07Add Constraint to SQL Table to ensure email contains @ 629 views
  8. 08Average of all values in a column that are not zero in SQL 584 views
  9. 09How to use Map Mode for Vertical Scroll Mode in Visual Studio 561 views
Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
Back to top
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com