Why C# ConcurrentDictionary has AddOrUpdate overload with addValueFactory method?

1 week ago 2
ARTICLE AD BOX

Is the AddOrUpdate overload that accepts addValueFactory used for cases when we want to ensure that an "expensive" object is instantiated only once?

AI says that it is useful for cases when you deal with expensive objects, so you create this expensive object only when an object with the given key doesn't exist in the concurrent dictionary.

I asked AI the next question: can't I just check beforehand if the object exists or not like this:

if (concurrentDictionary.TryGetValue(key, out var item)) { return item; }

Or like this:

concurrentDictionary.ContainsKey(key)

To which it answered that since it is a concurrent dictionary, somebody else can add an item with the same key concurrently, so that is why the concurrent dictionary will make inner checks and call my delegate (which creates the expensive object) only if the item does not exist.

Makes sense to me, but when I looked through the source code of ConcurrentDictionary I didn't manage to find out whether there are any checks if the key exists or not.

So do we really use the AddOrUpdate overload that accepts addValueFactory for cases when we want to make sure that we don't instantiate an expensive object more than one time?

Read Entire Article