Easily solve the problem of "collection has been modified": Avoid list modifications in the cycle
In the process of programming, when the "collection has been modified; the enumeration may not be executed" error, programmers are often confused, especially when the problem is still difficult to detect under the debugger. However, don't worry, the solution is to understand the potential list changes in the error cycle.
This error occurs when the element in the collection is modified when the circular set. In the WCF server code fragment, the "Subsidant" dictionary is modified in the "FOREACH" cycle of the "Notifysubscribers" method. Specifically, when the "Signaldata" method is indirectly modified, this error will be caused.
In order to solve this problem, we can use the "TOLIST ()" method to convert the value of the dictionary into a new list before the cycle, thereby avoiding the trap of the "modified". This will create a separate list independent of the original dictionary to ensure that changes to it during the cycle will not affect the iterative process.
The following is the method of adjusting the code:
By using this technology, the cycle no longer operates the original dictionary, but operates an independent copy. This eliminates the possibility of concurrent modification and prevents the annoying error of "collection has been modified".
<code class="language-c#">private static readonly IDictionary<Guid, Subscriber> subscribers = new Dictionary<Guid, Subscriber>(); ... public void NotifySubscribers(DataRecord sr) { foreach (Subscriber s in subscribers.Values.ToList()) // 将值复制到单独的列表中 { try { s.Callback.SignalData(sr); } catch ... } }</code>
The above is the detailed content of How to Resolve the 'Collection was modified' Error When Iterating Through a Dictionary in C#?. For more information, please follow other related articles on the PHP Chinese website!