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 a foreach Loop Over a List Throwing InvalidOperationException Because an Awaited Continuation Still Running After the Loop Started Modified the Same List

- 08.11.26 - ErcanOPAK

πŸ”§ C#: Fix a foreach Loop Over a List Throwing InvalidOperationException Because an Awaited Continuation Still Running After the Loop Started Modified the Same List

A foreach loop over a List<T> takes out an enumerator that detects structural modification to the underlying list during enumeration, throwing InvalidOperationException the moment it notices one. That’s usually understood as a single-threaded, same-call-stack mistake, but an await inside the loop body yields control back to the caller β€” and if some other async continuation already scheduled (a fire-and-forget task, an event handler) runs during that yielded gap and happens to modify the very same list, the loop throws on its next iteration with no obvious caller in the stack trace that looks like it modified a list during a foreach.

πŸ”Ž The Problem

private readonly List<Job> _jobs = new();

async Task ProcessAllAsync()
{
    foreach (var job in _jobs)
    {
        await job.RunAsync(); // yields here; some unrelated handler can now run and mutate _jobs
    }
}

// elsewhere, wired to an event that can fire during the await above:
void OnJobCancelled(object sender, JobEventArgs e) => _jobs.Remove(e.Job);

βœ… Fix: Isolate the Loop From Concurrent Mutation

  • Snapshot the collection before iterating with foreach (var job in _jobs.ToList()) (or ToArray()) whenever the loop body awaits, so later mutation of the live _jobs list can’t be observed by an enumerator walking a separate, already-copied sequence.
  • Audit what else is subscribed to run during the awaited call β€” an event handler, a timer callback, another in-flight task β€” specifically for whether it touches the same collection, since the real fix needs to address whichever side is doing the unexpected mutation, not just the loop that happens to notice it.
  • If the collection genuinely needs safe concurrent mutation during iteration, not just protection from this one case, use a collection type designed for it β€” a producer/consumer queue like ConcurrentQueue<T> β€” instead of mutating a List<T> that something else is actively enumerating.

🚨 Why This Is Dangerous

The exception’s stack trace points at the foreach line, which looks exactly like an ordinary β€œyou can’t modify a list while iterating it” bug in the same method β€” but the actual mutation happened in a completely different method, on a completely different code path, during the gap the await created, which can send debugging effort toward the wrong half of the codebase entirely.

An await doesn’t pause your code in a vacuum β€” it hands control back to everything else that’s waiting its turn, and anything in that everything-else can reach into the same list you thought only your loop was touching.

β€” C# Best Practice

Related posts:

C#: Fix a Generic Method's Type Inference Silently Picking the Base Class Overload Instead of the Mo...

C#: Fix a Generic Method's Type Inference Silently Picking the Base Class Overload Instead of the Mo...

C#: Fix a FrozenDictionary Lookup Returning the Wrong Value Because the Custom IEqualityComparer Use...

C#: Fix a FrozenDictionary Lookup Returning the Wrong Value Because the Custom IEqualityComparer Use...

C#: Use String Interpolation Instead of Concatenation

C#: Use String Interpolation Instead of Concatenation

Views: 8

Post navigation

ASP.NET Core: Fix a Minimal API Deserializing a Missing Property Into null Instead of Failing Because the Record’s Property Is Non-Nullable but Never Marked required
The AI Prompt That Turns a Production Incident’s Raw Log Timeline Into a Draft Postmortem’s Root-Cause Section

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 (857)
  • 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 @ (608)
  • 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 (546)
  • 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 (857)
  • 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