gpt4 book ai didi

c# - 并发词典的正确用法

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

我认为这是对并发字典的正确使用吗

private ConcurrentDictionary<int,long> myDic = new ConcurrentDictionary<int,long>();

//Main thread at program startup

for(int i = 0; i < 4; i++)
{
myDic.Add(i, 0);
}

//Separate threads use this to update a value

myDic[InputID] = newLongValue;

我没有锁等,只是更新字典中的值,即使多个线程可能正在尝试执行相同的操作。

最佳答案

这取决于线程安全的含义。

来自 MSDN - How to: Add and Remove Items from a ConcurrentDictionary :

ConcurrentDictionary<TKey, TValue> is designed for multithreaded scenarios. You do not have to use locks in your code to add or remove items from the collection. However, it is always possible for one thread to retrieve a value, and another thread to immediately update the collection by giving the same key a new value.

因此,可能会得到字典中某项值的不一致 View

关于c# - 并发词典的正确用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8225775/

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