Can I remove items from a ConcurrentDictionary from within an enumeration loop of that dictionary?
- by the-locster
So for example:
ConcurrentDictionary<string,Payload> itemCache = GetItems();
foreach(KeyValuePair<string,Payload> kvPair in itemCache)
{
if(TestItemExpiry(kvPair.Value))
{ // Remove expired item.
Payload removedItem;
itemCache.TryRemove(kvPair.Key, out removedItem);
}
}
Obviously with an ordinary Dictionary 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?