ConcurrentDictionary TryRemove何时返回false [英] When will ConcurrentDictionary TryRemove return false
问题描述
如果字典不包含给定键的值,它只会返回false还是由于线程争用条件而返回false,就像另一个线程添加/更新某些东西一样?
Will it only return false if the dictionary does not contain a value for the given key or will it also return false due to thread race conditions, like another thread adds/updates something?
代码中的问题:
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);
编辑:
我认为它只会返回false如果它不包含给定键的值,但要绝对确定。
I think that it only will return false if it does not contain a value for the given key, but want to be absolutely sure.
推荐答案
同时Mitch是正确的表示 ConcurrentDictionary
不容易受到比赛条件的影响,我认为您所提出的问题的答案是,是的,如果存在密钥, TryRemove
将起作用并返回 true
。
While Mitch is right that a ConcurrentDictionary
is not vulnerable to race conditions, I think the answer to the question you are asking is that yes, if the key is present, TryRemove
will work and will return true
.
在您发布的代码中, TryRemove $ c $是不可能的c>将返回
false
,因为 cd
是一个在其他任何地方都无法访问的局部变量。但是,如果其他地方的某些代码引用了此 ConcurrentDictionary
对象,并且正在删除单独线程上的键,则 TryRemove $ c即使在这里,$ c>仍可能返回
false
,但仅是因为密钥已被删除,而不是因为正在对密钥执行其他操作字典,并且密钥被卡在那里。
In the code you posted, there's no way that TryRemove
would return false
since cd
is a local variable not accessed anywhere else. But if some code elsewhere were given a reference to this ConcurrentDictionary
object and were removing keys on a separate thread, then it's possible that TryRemove
could return false
, even here -- but only because the key was already removed, not because some other action is being performed on the dictionary and the key is somehow "stuck" there.
这篇关于ConcurrentDictionary TryRemove何时返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!