我需要创建一个集合集合。该集合由多个线程调用以添加项目和查找项目。一旦添加,项目将不会被删除。目前,在添加元素时,我需要锁定整个集合。有没有办法让它无锁。或者我可以使用更好的数据结构或模式吗?这是我的代码的简化版本:
readonly ConcurrentDictionary<string, ConcurrentDictionary<int, int>> dict = new ConcurrentDictionary<string, ConcurrentDictionary<int, int>>();
void AddUpdateItem(string s, int k, int v)
{
ConcurrentDictionary<int, int> subDict;
if (dict.TryGetValue(s, out subDict))
{
subDict[k] = v;
}
else
{
lock (dict)
{
if (dict.TryGetValue(s, out subDict))
{
subDict[k] = v;
}
else
{
subDict = new ConcurrentDictionary<int, int>();
subDict[k] = v;
dict[s] = subDict;
}
}
}
}