例如:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
显然,对于普通的Dictionary,这将引发异常,因为删除项会在枚举的生命周期中更改字典的内部状态.我的理解是,并非ConcurrentDictionary的情况,因为提供的IEnumerable处理内部状态更改.我明白了吗?有更好的模式可供使用吗?