gpt4 book ai didi

c# - ConcurrentDictionary TryRemove 什么时候返回 false

转载 作者:IT王子 更新时间:2023-10-29 03:41:04 26 4
gpt4 key购买 nike

如果字典不包含给定键的值,它会只返回 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);

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

最佳答案

同时 Mitch is right ConcurrentDictionary 不易受竞争条件的影响,我认为您所问问题的答案是肯定的,如果 key 存在,TryRemove 将起作用并返回

在您发布的代码中,TryRemove 不可能返回 false,因为 cd 是无法在其他任何地方访问的局部变量。但是,如果其他地方的某些代码被赋予了对此 ConcurrentDictionary 对象的引用,并在单独的线程上删除键,则 TryRemove 可能会返回 false,即使在这里——但只是因为 key 已被删除,而不是因为正在对字典执行某些其他操作并且 key 以某种方式“卡”在那里。

关于c# - ConcurrentDictionary TryRemove 什么时候返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3519557/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com