字典并发访问的性能

Performance on concurrent accesses on a dictionary

我有一个具有以下行为的 Dictionary<string,string> :

我目前正在做以下事情。但我想知道是否有办法避免 TryGet 周围的锁?我的意思是我希望我的阅读表现最好。

    private readonly Dictionary<string, string> _mappings = new Dictionary<string, string>();

    public string GetValueByKey(string key)
    {
        bool valueFound;
        string value;
        lock (_mappings)
        {
            valueFound = _mappings.TryGetValue(key, out value);
        }

        if (valueFound)
        {
            return value;
        }

        var resolvedValue = ResolveValueForKey(key);
        lock (_mappings)
        {
            _mappings[key] = resolvedValue;//I don't care computing the value and set it several times
            return resolvedValue;
        }
    }

查看此页面上关于 thread-safe collectionsConcurrentDictionary

在内部,它为散列 table 中的每个 "bucket" 锁定。这意味着如果您的应用程序有大量并行读取,您可能会获得巨大的性能提升。在选择使用哪一个之前,您应该测量 Dictionary 以查看性能是否符合要求 table,如果不符合,则测量 ConcurrentDictionary 以查看您是否获得了性能。