简体   繁体   中英

System.InvalidOperationException: Collection was modified; enumeration operation may not execute

I'm having a problem when getting the tempkey which is the source loaded from another function. Normally the source contains 18 to 20 keys randomly. This problem happens once in awhile. How to access the source keys without getting exception error like " Collection was modified; enumeration operation may not execute" .

private static IDictionary<string, BitArray> source;

public bool Check()
{
    string tempKey = source.Keys.FirstOrDefault(k => k.EndsWith(key));   
}

One option is to use ConcurrentDictionary or ImmutableDictionary .

ConcurrentDictionary 's Keys accessor returns a copy of the keys collection which you can than inspect even if other code is modifying the original dictionary.


Note 1. Dictionary 's doco (the not Concurrent flavour) explicitly talks about thread-safety and the situation you encounered

(...) enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with write accesses, the collection must be locked during the entire enumeration.

I recommend reading the whole short section on Dictionary's Thread Safety .


Note 2. You can be tempted to ToList() source.Keys which will improve the situation (the exception will seem to go away, mostly), but it won't fix the issue for good.

This exception occur when your code is modifying the collection and within same code block or thread you are also trying to iterate the collection or put where condition on it.

Best way to avoid is to do the modifications on the collection first. And after doing all the modification(add/remove etc) then you check the collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM