ConcurrentDictionary替代可移植类库

Tho*_*que 9 c# collections concurrency caching thread-safety

我正在编写一个面向.NET 4.5,Windows应用商店应用程序和Windows Phone 8的可移植类库.我需要一个高效的内存缓存机制,因此我在考虑使用ConcurrentDictionary<K,V>,但它在WP8中不可用.

将有许多读取和相对较少的写入,所以理想情况下我想要一个支持来自多个线程的无锁读取的集合,并由单个线程写入.根据MSDN,非泛型Hashtable具有该属性,但不幸的是它在PCL中不可用...

PCL中是否有另一个符合此要求的集合类?如果没有,那么在不锁定读取的情况下实现线程安全的好方法是什么?(锁定写入是可以的,因为它不会经常发生)


编辑:感谢JaredPar的指导下,我终于实现我的缓存在一个完全无锁的方式,利用ImmutableDictionary<TKey, TValue>Microsoft.Bcl.Immutable:

class Cache<TKey, TValue>
{
    private IImmutableDictionary<TKey, TValue> _cache = ImmutableDictionary.Create<TKey, TValue>();

    public TValue GetOrAdd(TKey key, [NotNull] Func<TKey, TValue> valueFactory)
    {
        valueFactory.CheckArgumentNull("valueFactory");

        TValue newValue = default(TValue);
        bool newValueCreated = false;
        while (true)
        {
            var oldCache = _cache;
            TValue value;
            if (oldCache.TryGetValue(key, out value))
                return value;

            // Value not found; create it if necessary
            if (!newValueCreated)
            {
                newValue = valueFactory(key);
                newValueCreated = true;
            }

            // Add the new value to the cache
            var newCache = oldCache.Add(key, newValue);
            if (Interlocked.CompareExchange(ref _cache, newCache, oldCache) == oldCache)
            {
                // Cache successfully written
                return newValue;
            }

            // Failed to write the new cache because another thread
            // already changed it; try again.
        }
    }

    public void Clear()
    {
        _cache = _cache.Clear();
    }
}
Run Code Online (Sandbox Code Playgroud)

Jar*_*Par 4

可以考虑的一个选择是在不可变的搜索树上编写一个薄的外观。网络上有几种不可变的搜索树可供选择。我通常以 Eric Lipperts 关于该主题的精彩帖子为基础

使用它作为支持数据结构将为您提供无锁。对树的写入也可以使用 CAS 以无锁方式完成。这会慢一点,ConcurrentDictionary因为查找的时间复杂度为 O(Log(N)),而不是接近 O(1)。但它应该对你有用