I have a ConcurrentDictionary that I want to empty, copying its content into a dictionary (or any other container) while emptying it at the same time.
A key invariant is that no element from the source is lost during the operation.
My current code looks like this:
private Dictionary<TKey, TValue> Foo<TKey, TValue>(ConcurrentDictionary<TKey, TValue> source)
{
var result = new Dictionary<TKey, TValue>();
foreach (var item in source)
{
result[item.Key] = item.Value;
}
source.Clear();
return result;
}
From my understanding, this code is thread-safe but any element added concurrently after the foreach loop and before the Clear() will be cleared.
edit: some more precisions. In my use case, that code is the only one that does remove keys some the dictionary; other threads only ever TryAdd or AddOrUpdate.