Why does Concurrent Dictionary not have a visible Add() Method?

前端 未结 2 1477
梦如初夏
梦如初夏 2021-01-12 07:41

I was just wondering how it was possible that ConcurrentDictionary does not have an Add method which is visible in the Visual Studio IDE. I only seem to get the TryX Methods

2条回答
  •  一生所求
    2021-01-12 07:43

    They are discouraging the use of the Add method because the method throws an exception if the key is already present in the dictionary. For most dictionaries, the developer can write code in a way to guarantee that the exception will not be thrown under any normal scenario. However, to perform this operation (Contains followed by Add) with a concurrent dictionary, you would need to use exclusive locks in methods accessing the dictionary, which defeats the entire purpose of a concurrent dictionary.

    TryAdd combines the Contains and Add checks without requiring you to lock the dictionary, and allows you to once again write code that won't throw an exception in normal scenarios.

提交回复
热议问题