Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

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

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

C#: Fix an Async Local Function Still Capturing a Loop Variable by Reference Even Though the Outer Loop Already Uses Per-Iteration Scoping

- 31.10.26 - ErcanOPAK

🔧 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.

— C# Best Practice

Related posts:

C#: Fix a Static Field That Silently Resets Between Test Runs in the Same Process

C#: Fix a Static Field That Silently Resets Between Test Runs in the Same Process

C# — Async State Machines Increase Memory Usage

C# — Async State Machines Increase Memory Usage

C#: Use Null-Coalescing Operator for Null Safety

C#: Use Null-Coalescing Operator for Null Safety

Views: 10

Post navigation

WordPress: Fix a Multisite Network’s Shared Plugin Settings Leaking Into a Subsite Because switch_to_blog Was Never Restored Afterward
WordPress: Fix a Custom Taxonomy’s Terms Not Appearing in the Site’s Own Search Results Because the Taxonomy Was Registered With exclude_from_search Left at Its Default

Leave a Reply Cancel reply

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

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (980)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (653)
  • Add Constraint to SQL Table to ensure email contains @ (609)
  • Average of all values in a column that are not zero in SQL (570)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (547)
  • Find numbers with more than two decimal places in SQL (475)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit
  • SQL Server: Fix ROW_NUMBER Ties Reordering Between Identical Runs
  • C#: Fix an Enum HasFlag Returning True for the Zero Value
  • WordPress: Fix Featured Images Vanishing After a CDN Migration
  • Photoshop: Fix Content-Aware Fill Smearing a Repeating Pattern
  • Asp.Net Core: Fix Antiforgery Tokens Rejected Behind a Reverse Proxy

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (980)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit

Social

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