Home > Backend Development > C++ > How to Resolve the 'Collection was modified' Error When Iterating Through a Dictionary in C#?

How to Resolve the 'Collection was modified' Error When Iterating Through a Dictionary in C#?

Susan Sarandon
Release: 2025-02-02 03:41:09
Original
938 people have browsed it

How to Resolve the

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template