1

我一直在研究如何在我的类库中实现基本的内存缓存。我遇到了这个例子并决定实现类似的东西,但我遇到了一些问题:

  • 真的是MemoryCache线程安全的吗?浏览评论,我发现有人说,有人说不是。我以前从未使用过这个类,所以我不确定哪些评论适用于我的情况。
  • 如果MemoryCache不是线程安全的,如何使它成为线程安全的?还是我应该针对我的情况使用不同的东西?

在我的情况下,消费应用程序将有一个我的类 ( DataProviderDecorator) 的实例,由1N个线程使用。以这种方式使用是否安全?:

public class DataProviderDecorator : IDataProvider
{
    private readonly IDataProvider Decoratee;
    private readonly MemoryCache Cache;                                         // System.Runtime.Caching.MemoryCache
    private ConcurrentDictionary<string, SemaphoreSlim> Locks { get; set; }     // System.Collections.Concurrent.ConcurrentDictionary and System.Threading.SemaphoreSlim

    public object GetItem(string key)
    {
        object result = null;

        if (Cache.Contains(key))
        {
            return Cache.Get(key);
        }

        SemaphoreSlim cacheLock = Locks.GetOrAdd(key, new SemaphoreSlim(1, 1));
        cacheLock.Wait();

        try
        {
            if (Cache.Contains(key))
            {
                return (QueryResult)Cache.Get(key);
            }

            result = Decoratee.GetItem(key);

            CacheItemPolicy cacheItemPolicy = new CacheItemPolicy();
            cacheItemPolicy.SlidingExpiration = new TimeSpan(0, 0, 30);
            if (!Cache.Add(key, result, cacheItemPolicy))
            {
                throw new Exception($"A record for the key [{key}] is already present in the cache.");
            }
        }
        finally
        {
            cacheLock.Release();
        }

        return result;
    }
}

另外,有没有人知道我应该如何维护锁的集合?估计它会无限期地填满。

4

0 回答 0