Reputation: 5
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));
}
Upvotes: 0
Views: 1094
Reputation: 669
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.
Upvotes: 0
Reputation: 34947
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.
Upvotes: 3