gpt4 book ai didi

c# - 更新 ConcurrentDictionary 中的列表

转载 作者:太空狗 更新时间:2023-10-29 21:12:02 30 4
gpt4 key购买 nike

所以我有一个 IList 作为我的 ConcurrentDictionary 中的值。

ConcurrentDictionary<int, IList<string>> list1 = new ConcurrentDictionary<int, IList<string>>;

为了更新列表中的值,我这样做:

if (list1.ContainsKey[key])
{
IList<string> templist;
list1.TryGetValue(key, out templist);
templist.Add("helloworld");
}

但是,将字符串添加到 templist 是否会更新 ConcurrentDictionary?如果是这样,更新是否线程安全以便不会发生数据损坏?

或者是否有更好的方法在 ConcurrentDictionary 中更新或创建列表

编辑

如果我要使用 ConcurrentBag 而不是 List,我将如何实现它?更具体地说,我该如何更新它? ConcurrentDictionary 的 TryUpdate 方法感觉有点过分。

ConcurrentBag.Add 是否以线程安全的方式更新 ConcurrentDictionary?

ConcurrentDictionary<int, ConcurrentBag<string>> list1 = new ConcurrentDictionary<int, ConcurrentBag<string>>

最佳答案

首先,没有必要做 ContainsKey() TryGetValue() .

你应该这样做:

IList<string> templist;

if (list1.TryGetValue(key, out templist))
templist.Add("helloworld");

事实上,您编写的代码存在竞争条件。

在一个线程调用 ContainsKey() 之间和 TryGetValue()另一个线程可能已经删除了具有该键的项目。那么TryGetValue()将返回 tempList为 null,然后当你调用 tempList.Add() 时你会得到一个 null 引用异常.

其次,是的:这里还有另一个可能的线程问题。你不知道 IList<string>存储在字典中是线程安全的。

因此调用tempList.Add()不保证安全。

你可以使用 ConcurrentQueue<string>而不是 IList<string> .这可能是最可靠的解决方案。

请注意,只需锁定对 IList<string> 的访问还不够。

这不好:

if (list1.TryGetValue(key, out templist))
{
lock (locker)
{
templist.Add("helloworld");
}
}

除非你在其他地方也使用与 IList 相同的锁可以访问。这不容易实现,因此最好使用 ConcurrentQueue<>或向此类添加锁定并更改体系结构,以便其他线程无法访问底层 IList。

关于c# - 更新 ConcurrentDictionary 中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41592129/

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