gpt4 book ai didi

c# - 检查元素是否存在于多线程应用程序的集合中

转载 作者:太空狗 更新时间:2023-10-30 01:05:16 25 4
gpt4 key购买 nike

假设我们有两个线程和一个集合:

ConcurrentDictionary<int, object[]> lists = new ConcurrentDictionary<int, object[]>();

1) 一个线程处理集合中的元素,然后从集合中移除元素

foreach(object[] elem in lists.Values)
{
//do somethind
lists.TryRemove(key, out vals);
}

2) 第二个线程向集合中添加元素,然后它需要能够检查元素状态:

lists.Add(10, some_object);

...

if(lists.ContainsKey(10))
{

//How can I be sure that at this moment element is still exists ?
//Thread may be preempted after if() {} and second thread
//can remove object from collection
}

最佳答案

你应该使用 TryGetValue ,因为这确保检查/获取是原子的:

object[] val;
if(lists.TryGetValue(10, out val)) {
// Here you have a reference to the object[], even if it has subsequently been removed
}

当然,object[]本身的线程安全是另外一个问题,不是ConcurrentDictionary可以解决的。 (例如,如果说两个线程都以某种方式修改对象,并且对象不是线程安全的,那么您需要在 TryGetValue block 内使用锁。)

关于c# - 检查元素是否存在于多线程应用程序的集合中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19437019/

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