Why does ConcurrentDictionary.GetOrAdd(key, valueFactory) allow the valueFactory to be invoked twice?

前端 未结 2 689
梦谈多话
梦谈多话 2020-12-08 04:36

I am using a concurrent dictionary as a thread-safe static cache and noticed the following behavior:

From the MSDN docs on GetOrAdd:

If you ca

2条回答
  •  -上瘾入骨i
    2020-12-08 05:19

    This is not uncommon with Non-Blocking Algorithms. They essentially test for a condition confirming there is no contention using Interlock.CompareExchange. They loop around though until the CAS succeeds. Have a look at ConcurrentQueue page (4) as a good intro to Non-Blocking Algorithms

    Short answer is no, it's the nature of the beast that it will require multiple attempts to add to the collection under contention. Other than using the other overload of passing a value, you'd need to protect against multiple calls inside your value factory, perhaps using a double lock / memory barrier.

提交回复
热议问题