gpt4 book ai didi

c# - 为并发锁定 HashSet

转载 作者:太空狗 更新时间:2023-10-30 00:14:07 24 4
gpt4 key购买 nike

<分区>

使用 HashSet<string> 时检查之前是否处理过某个项目(即仅使用 AddContains)。此外,它不相关,当 Contains 返回 false 时,即使它是在 ...

我在没有锁定的情况下遇到了以下异常:

[IndexOutOfRangeException: Index was outside the bounds of the array.] System.Collections.Generic.HashSet`1.AddIfNotPresent(T value) +6108128

仅锁定 Add 调用就足够了吗?

以下似乎永远有效 - 但这不是证据......

HashSet<string> hashSet = new HashSet<string>();
Parallel.ForEach(GetString(), h =>
{
hashSet.Contains(h);
lock(hashSetLock)
{
hashSet.Add(h);
}
hashSet.Contains(h);
});

准确地说:我知道调用 Contains 不是线程安全的没有锁。我的问题是(接受误报)如果上面的代码会抛出异常或者会破坏底层数据结构 (=HashSet) 的内部状态。

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