How to iterate on a ConcurrentDictionary: foreach vs Keys/Values

 
 
  • Gérald Barré

There are multiple ways to iterate on a ConcurrentDictionary<TKey, TValue> in .NET. You can use the foreach loop, or the Keys and Values properties. Both methods provide different results, and you should choose the one that best fits your needs.

#Using the foreach loop

The foreach loop lazily iterates over the key-value pairs in the ConcurrentDictionary. This means that the loop will only fetch the next key-value pair when it is needed. Also, it's enumerate live data. So, if you add an entry while iterating on the dictionary, the foreach loop may return it. Another interesting point is that the enumeration doesn't lock the dictionary. So, it doesn't impact the performance.

C#
var dictionary = new ConcurrentDictionary<int, string>();
foreach (var pair in dictionary)
{
    Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}");
}

#Using the Keys and Values properties

The Keys and Values properties return a snapshot of the keys and values in the dictionary. This means that the collection returned by these properties is a copy of the keys and values at the time of the call. So, if you add an entry while iterating on the dictionary, the Keys and Values properties won't return it. Also, the Keys and Values properties lock the dictionary while they are being accessed. This can impact the performance if the dictionary is large.

C#
var dictionary = new ConcurrentDictionary<int, string>();
foreach (var key in dictionary.Keys)
{
    Console.WriteLine($"Key: {key}");
}

#Conclusion

foreach / GetEnumerator

  • Lazily iterates over the key-value pairs
  • Enumerate live data
  • Doesn't lock the dictionary

Keys / Values

  • Returns a snapshot of the keys and values
  • Doesn't enumerate live data
  • Locks the dictionary

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub