🔧 Fix an Async Local Function Still Capturing a Loop Variable by Reference Even Though the Outer Loop Already Uses Per-Iteration Scoping
Modern C# gives a foreach loop’s iteration variable a fresh scope on every single iteration, which is exactly the fix that made the old closure-captures-the-wrong-loop-value bug mostly disappear for straightforward cases, a lambda created inside a foreach now correctly captures that iteration’s own value rather than one shared variable mutated across the whole loop. That per-iteration scoping applies to the loop variable itself, though, not automatically to every other local variable declared inside the loop body, and an async local function that captures a separate local variable, one declared once inside the loop body but outside any per-iteration construct, still closes over that single shared variable exactly like closures always have, which can look deceptively identical to the now-fixed loop-variable case while actually being the completely unrelated, still-very-real bug it always was.
🔎 The Problem
var tasks = new List<Task>();
foreach (var item in items) // per-iteration scoping: 'item'
// itself is safe to capture
{
int retryCount = 0; // declared ONCE per iteration body,
// but this is a regular local, not
// the loop variable -- its own
// "freshness" depends on normal
// scoping rules, not the special
// per-iteration behavior 'item' gets
async Task ProcessWithRetry()
{
while (retryCount < 3)
{
try { await ProcessAsync(item); return; }
catch { retryCount++; } // captures 'retryCount' by
// reference, same as always
}
}
tasks.Add(ProcessWithRetry());
}
await Task.WhenAll(tasks);
// 'item' is correctly distinct per task, thanks to per-iteration
// loop-variable scoping -- but if ProcessWithRetry's closure were
// ever restructured to also need a variable shared more broadly,
// or if retryCount were hoisted outside the loop by a future edit,
// the SAME kind of shared-mutable-state bug the loop variable fix
// solved for 'item' specifically can still happen for any other
// captured local that isn't the loop variable itself
✅ Fix: Know Exactly Which Variable the Per-Iteration Fix Actually Covers
- Remember that C#’s per-iteration foreach scoping applies specifically to the loop’s own iteration variable, not to every local variable declared anywhere inside the loop body, so don’t assume a closure problem is impossible inside a foreach just because the classic loop-variable version of that bug was fixed years ago.
- For any local variable inside a loop body that an async local function or lambda captures and also mutates, declare it fresh inside that same iteration explicitly if each task needs its own independent copy, rather than relying on it happening to be declared once per pass through the loop body.
- When a Task.WhenAll result shows fewer distinct outcomes than the number of items processed, or state that looks shared across tasks that should be independent, check specifically which local variables each async local function or lambda is capturing, since the loop variable itself is very unlikely to be the culprit anymore, but every other captured local still is exactly as capturable-by-reference as it always was.
🚨 Why This Is Dangerous
- Knowing that the classic foreach closure bug was fixed for the loop variable can create a false sense that closures inside loops are now generally safe, which leaves exactly this kind of bug, a non-loop-variable local shared across concurrent async tasks, looking unlikely to a reviewer who remembers the old bug being fixed but doesn’t realize the fix never covered this specific variable at all.
Per-iteration scoping fixed one specific variable’s behavior inside a foreach loop, the loop variable itself, and every other local you declare in that same loop body is exactly as shared and exactly as capturable as it would have been before that fix ever shipped.
