Is this the proper way to iterate over Concurrentdictionary in C#
is this the safe way of iterating over a concurrent dictionary? If not, what is the safe way for doing it?
Yes, it's safe in that it won't throw an exception. If elements are added or removed after you start iterating, they may or may not be included in the iteration. From the GetEnumerator
documentation:
The enumerator returned from the dictionary is safe to use concurrently with reads and writes to the dictionary, however it does not represent a moment-in-time snapshot of the dictionary. The contents exposed through the enumerator may contain modifications made to the dictionary after GetEnumerator was called.
Next:
I use the tryRemove method, but what do I do with the outPerson object?
Whatever you want with it, including nothing. You could just cast the dictionary to IDictionary<TKey, TValue>
and call Remove
, or just use TryRemove
and ignore the variable afterwards:
Person ignored;
dictionary.TryRemove(key, out ignored);
Or you can use C# 7.0 feature Discards
dictionary.TryRemove(key, out _);
There's no concept of "clearing [the object] completely" - if you haven't got any references to it, it will be garbage collected. But either way, it's not in the dictionary any more (at least via that key). If you don't use the variable (ignored
above) anywhere else in the code, it won't stop the object from being garbage collected.
Take a look at this article.
TryRemove() was added to attempt atomic, safe removes.
To safely attempt to remove a value we need to see if the key exists first, this checks for existence and removes under an atomic lock.
Since TryRemove will remove the item from collection, you might need the value of the key.
It is safe to iterate it with foreach. You wont get an exception.