C#嵌套的ConcurrentDictionary包装器

时间:2018-06-17 22:57:29

标签: c# c#-7.0

似乎没有办法嵌套ConcurrentDictionary以便它们共享一个锁

我正在尝试创建一个包含带有锁

的3深嵌套字典的类

这样我就可以做NestedDict [k1] [k2] [k3]并以并发安全方式获取值 并执行NestedDict [k1] [k2]并获取ConcurrentDictionary或等效项。

我不是在寻找继承或撰写ConcurrentDictionary<Tuple<TK1,TK2,TK3>,V>的解决方案,因为它不相同,它不允许我有效地获取dict的所有键[k1,k2]

如何实施?

是否存在显示此类嵌套字典实现(包括迭代器等)的现有通用库/代码?

1 个答案:

答案 0 :(得分:2)

您可以采取以下方法

using System;
using System.Collections.Concurrent;

public class Program
{
    public class NestedDictionary<TK1, TK2, TK3, TValue>
    {
        private readonly ConcurrentDictionary<Tuple<TK1, TK2, TK3>, TValue> storage = new ConcurrentDictionary<Tuple<TK1, TK2, TK3>, TValue>();
        public TValue this[TK1 key1, TK2 key2, TK3 key3]
        {
            get => this.storage[new Tuple<TK1, TK2, TK3>(key1, key2, key3)];
            set => this.storage[new Tuple<TK1, TK2, TK3>(key1, key2, key3)] = value;
        }

        public bool TryGetValue(TK1 key1, TK2 key2, TK3 key3, out TValue value)
        {
            return this.storage.TryGetValue(new Tuple<TK1, TK2, TK3>(key1, key2, key3), out value);
        }

        public bool TryAdd(TK1 key1, TK2 key2, TK3 key3, TValue value)
        {
            return this.storage.TryAdd(new Tuple<TK1, TK2, TK3>(key1, key2, key3), value);
        }

        // etc etc

    }

    public static void Main()
    {
        NestedDictionary<int, bool, DateTime, string> d = new NestedDictionary<int, bool, DateTime, string>();
        d[1, false, new DateTime(2018, 6, 18)] = "Hello";
        d[1, true, new DateTime(2018, 6, 18)] = "World";
        d[2, false, new DateTime(2018, 6, 18)] = "Foo";
        d[2, false, new DateTime(2018, 6, 19)] = "Bar";
        Console.WriteLine(d[1, true, new DateTime(2018, 6, 18)]); // World
    }
}

你甚至可以在appch上实现IDictionary方法。鉴于Tuple内部通过复合键在您的哈希码上提供了很好的传播,它应该具有非常类似于嵌套中三个单独词典的性能特征。