何时ConcurrentDictionary将TryRemove返回false

Mar*_*sen 73 .net c# concurrency

如果字典不包含给定键的值,它是否只返回false,或者由于线程竞争条件它也会返回false,就像另一个线程添加/更新某些东西一样?

代码问题:

ConcurrentDictionary<int, string> cd = new ConcurrentDictionary<int, string>();

// This might fail if another thread is adding with key value of 1.
cd.TryAdd(1, "one"); 

// Will this ever fail if no other thread ever removes with the key value of 1?
cd.TryRemove(1); 
Run Code Online (Sandbox Code Playgroud)

编辑: 我认为它只会返回false,如果它不包含给定键的值,但想要绝对确定.

Dan*_*Tao 75

虽然米奇是正确的,因为a ConcurrentDictionary不容易受到竞争条件的影响,但我认为你要问的问题的答案是肯定的,如果钥匙存在,TryRemove它将起作用并将返回true.

在您发布的代码中,TryRemove无法返回,false因为cd本地变量无法在其他任何地方访问.但是,如果其他地方的某些代码被赋予对该ConcurrentDictionary对象的引用并且正在删除单独线程上的键,则可能TryRemove会返回false,即使在此处 - 但仅仅因为该键已被删除,而不是因为正在执行某些其他操作字典和密钥以某种方式"卡住"在那里.


Mit*_*eat 5

ConcurrentDictionary不从比赛条件受到影响.这就是你使用它的原因.

回报价值

如果成功删除了对象,则为true; 否则,错误.