要修复编译器错误,您可以这样做:
myDic.AddOrUpdate(1, new HashSet<int>() { myFirstElement },
(key, actualValue) => {
actualValue.Add(myFirstElement);
return actualValue;
});
但是这不是线程安全的,因为“更新”功能不在任何锁内运行,因此您可能会从多个线程添加到非线程安全的HashSet。这可能会导致(例如)丢失值(例如,您将 1000 个项目添加到 HashSet 但最后您只有 970 个项目)。 AddOrUpdate 中的更新功能不应该有任何副作用,这里确实有。
您可以锁定自己,无法向HashSet 添加值:
myDic.AddOrUpdate(1, new HashSet<int>() { myFirstElement },
(key, actualValue) => {
lock (actualValue) {
actualValue.Add(myFirstElement);
return actualValue;
}
});
但是问题是你为什么首先使用无锁结构(ConcurrentDictionary)。除此之外 - 任何其他代码都可能从您的字典中获得HashSet 并在没有任何锁的情况下在那里添加价值,从而使整个事情变得无用。因此,如果您出于某种原因决定采用这种方式 - 在从该字典访问 HashSet 时,您必须确保所有代码锁定。
而不是所有这些 - 只需使用并发收集而不是 HashSet。据我所知,没有ConcurrentHashSet,但您可以使用另一个带有虚拟键的ConcurrentDictionary 作为替代品(或在互联网上查看自定义实现)。
旁注。这里
myDic.AddOrUpdate(1, new Hashset<int>(){myFirstElement},
每次调用AddOrUpdate 时都会创建新的HashSet,即使不需要该字典,因为密钥已经存在。而是使用带有增值工厂的重载:
myDic.AddOrUpdate(1, (key) => new HashSet<int>() { myFirstElement },
编辑:ConcurrentDictionary 作为哈希集的示例用法:
var myDic = new ConcurrentDictionary<long, ConcurrentDictionary<int, byte>>();
long key = 1;
int element = 1;
var hashSet = myDic.AddOrUpdate(key,
_ => new ConcurrentDictionary<int, byte>(new[] {new KeyValuePair<int, byte>(element, 0)}),
(_, oldValue) => {
oldValue.TryAdd(element, 0);
return oldValue;
});