You can use the TryRemove(key, out value) method. It returns the deleted item. This way, you do not need to lock the dictionary to move buffered data.
List<data> list; var keys = dict.Keys; foreach(var key in keys) { data value; dict.TryRemove(key, out value); list.Add(value); }
Update: in fact, you can iterate directly over the ConcurrentDictionary , even if it changes. This way you do not need to create a key collection from the .Keys property, which can be (?) Slow, depending on the implementation.
List<data> list; foreach(var kvp in dict) { data value; dict.TryRemove(kvp.Key, out value); list.Add(value); }
source share