π§ 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())(orToArray()) 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.
