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 an IAsyncEnumerable Loop Leaking a Connection on Break

- 27.11.26 - ErcanOPAK

🔧 C#: Fix an IAsyncEnumerable Loop Leaking a Connection on Break

An await foreach loop over an IAsyncEnumerable<T> that exits early via break or return relies on the compiler-generated enumerator’s DisposeAsync() being called to release whatever resource the generator method opened — a database reader, a file stream, an HTTP response body. That disposal does happen automatically for a normal await foreach, but a manual enumeration using GetAsyncEnumerator() directly, without a corresponding try/finally calling DisposeAsync(), silently skips it the moment the loop body throws or returns before reaching the end.

🔎 The Problem

var enumerator = GetRowsAsync(connection).GetAsyncEnumerator();
while (await enumerator.MoveNextAsync())
{
    if (enumerator.Current.Id == targetId)
        return enumerator.Current; // early return, no DisposeAsync()
}
// underlying SqlDataReader / connection scope never gets disposed -
// connection pool slowly exhausts under load

✅ Fix: Let await foreach Manage Disposal, or Do It Yourself

  • Prefer a plain await foreach over manual GetAsyncEnumerator() calls whenever possible — the compiler wraps it in the equivalent of a try/finally automatically, including on break or an early return inside the loop.
  • If manual enumeration is unavoidable (holding a reference across multiple method calls, for instance), wrap it in await using var enumerator = ... so DisposeAsync() is guaranteed to run regardless of how the method exits.
  • Add a connection pool metric or alert for ‘connections opened vs. disposed’ in staging — a slow leak like this often doesn’t show up under light local testing but becomes visible quickly under real concurrent load.

🚨 Why This Is Dangerous

  • A method that works perfectly in every manual test, because each call happens to reach the natural end of its loop, can still leak one connection per call on the specific, less-common early-exit path — exhausting the pool only under production traffic patterns that trigger that branch repeatedly.

await foreach cleans up after itself by design — step outside of it and that cleanup is a promise you now have to keep yourself.

— C# Best Practice

Related posts:

C#: Fix a Record's with Expression Not Cloning a Nested Collection

C#: Fix a Record's with Expression Not Cloning a Nested Collection

C#: Fix a yield break Inside a try Block Silently Delaying the finally Clause Until the Iterator Is ...

C#: Fix a yield break Inside a try Block Silently Delaying the finally Clause Until the Iterator Is ...

C#: Fix a required Member the Compiler Enforces at Construction but a Reflection-Based Deserializer ...

C#: Fix a required Member the Compiler Enforces at Construction but a Reflection-Based Deserializer ...

Views: 8
Found this useful? Share it
XLinkedInWhatsApp

Post navigation

Ajax: Fix an Aborted Request Still Triggering Its Success Callback
WordPress: Fix Featured Images Missing on the AMP Version of a Post

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 996 views
  3. 03Get the User Name and Domain Name from an Email Address in SQL 995 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# 866 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