🔧 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 foreachover manualGetAsyncEnumerator()calls whenever possible — the compiler wraps it in the equivalent of atry/finallyautomatically, including onbreakor an earlyreturninside the loop. - If manual enumeration is unavoidable (holding a reference across multiple method calls, for instance), wrap it in
await using var enumerator = ...soDisposeAsync()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.



