gpt4 book ai didi

c# - 试图了解 ConcurrentDictionary 的工作原理

转载 作者:太空宇宙 更新时间:2023-11-03 20:01:05 26 4
gpt4 key购买 nike

如果值不存在,我想将其初始化为 0。否则它应该增加现有值。

ConcurrentDictionary<int, int> dic = new ConcurrentDictionary<int, int>();
dic.AddOrUpdate(1, 0, (key, old) => old++);
dic.AddOrUpdate(2, 0, (key, old) => old++);

此时,字典的键值为 1 和 2,值为 0。

        dic.AddOrUpdate(1, 0, (key, old) => old++);

此时键 1 的值应为 1,而键 2 的值应为 0,但是两者的值均为 0。知道为什么吗?

最佳答案

你有一个误解:

dic.AddOrUpdate(1, 0, (key, old) => old++);

At this point for the key 1 the value should be 1

当您使用 old++ 时,它返回要存储的修改之前的原始值。这就好像你做了等同于:

dic.AddOrUpdate(1, 0, (key, old) => 
{
var original = old;
old = old + 1;
return original;
});

你想要 ++old 它将返回修改后的值或只使用

dic.AddOrUpdate(1, 0, (key, old) => old + 1);

关于c# - 试图了解 ConcurrentDictionary 的工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28219501/

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