9

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

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

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


编辑:感谢 JaredPar 的指导,我最终使用 Microsoft.Bcl.Immutable 以完全无锁的方式实现了我ImmutableDictionary<TKey, TValue>缓存

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();
    }
}
4

1 回答 1

4

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

使用它作为后备数据结构将使您无锁。对树的写入也可以使用 CAS 以无锁方式完成。这会比ConcurrentDictionary因为查找是 O(Log(N)) 而不是接近 O(1) 慢一点。但它应该为你解决问题

于 2013-08-21T23:38:45.323 回答