The error "Collection was modified; enumeration operation may not execute" arises when a foreach
loop iterates over a collection that's modified during the loop's execution. This often happens when adding or removing items from the collection within the loop itself, or from another thread.
The provided example shows this error in a NotifySubscribers()
method iterating through a subscribers
dictionary. The problem stems from the SignalData
method, which might indirectly modify the subscribers
dictionary while NotifySubscribers()
is running. This could happen if SignalData
triggers subscriber additions or removals.
The solution is to create a copy of the collection before entering the loop. This prevents modification of the original collection from affecting the loop's iteration:
<code class="language-csharp">foreach (Subscriber s in subscribers.Values.ToList()) { // Notify subscriber s }</code>
Using ToList()
creates a new list containing a snapshot of the subscribers.Values
. The foreach
loop now operates on this independent copy, ensuring that modifications to the original subscribers
dictionary won't cause the error. This guarantees safe and reliable enumeration.
The above is the detailed content of Why Does My `foreach` Loop Throw a 'Collection was modified; enumeration operation may not execute' Error?. For more information, please follow other related articles on the PHP Chinese website!