So for example:
ConcurrentDictionary<string,Payload> itemCache = GetItems();
foreach(KeyValuePair<string,Payload> kvPair in itemCache)
{
if(TestItemExpiry(kvPair.Value))
{ // Remove expired item.
itemCache.TryRemove(kvPair.Key, out Payload removedItem);
}
}
Obviously with an ordinary Dictionary<K,V> this will throw an exception, because removing items changes the dictionary’s internal state during the life of the enumeration. It’s my understanding that this is not the case for a ConcurrentDictionary, as the provided IEnumerable handles internal state changing. Am I understanding this right? Is there a better pattern to use?
It’s strange to me that you’ve now received two answers that seem to confirm you can’t do this. I just tested it myself and it worked fine without throwing any exception.
Below is the code I used to test the behavior, followed by an excerpt of the output (around when I pressed ‘C’ to clear the dictionary in a
foreachandSimmediately afterwards to stop the background threads). Notice that I put a pretty substantial amount of stress on thisConcurrentDictionary: 16 threading timers each attempting to add an item roughly every 15 milliseconds.It seems to me this class is quite robust, and worth your attention if you’re working in a multithreaded scenario.
Code
Output (excerpt)
Also note that, based on the console output, it looks like the
foreachloop locked out the other threads that were trying to add values to the dictionary. (I could be wrong, but otherwise I would’ve guessed you would’ve seen a bunch of “Added entry” lines between the “COUNT” lines.)