Can I remove items from a ConcurrentDictionary from within an enumeration loop of that dictionary?

Posted by the-locster on Stack Overflow See other posts from Stack Overflow or by the-locster
Published on 2010-02-23T12:22:28Z Indexed on 2010/04/28 11:23 UTC
Read the original article Hit count: 487

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?

© Stack Overflow or respective owner

Related posts about .NET

Related posts about parallel-extensions