【问题标题】:What is the common pattern to use MemoryCache instead of ConccurentDictionary?使用 MemoryCache 代替 ConccurentDictionary 的常见模式是什么?
【发布时间】:2015-12-25 13:16:53
【问题描述】:

我的代码通过等待已经运行的操作的结果来处理并发请求。数据请求可能同时带有相同/不同的凭据(包括空凭据)。

对于每组唯一的凭据,最多可以有一个正在进行的 GetDataInternal 调用,当它准备好时,该调用的结果会返回给所有排队的服务员

private static readonly Credentials EmptyCredentials = 
new Credentials
{
    SqlCredentials = null,
    ExchangeCredentials = null
}; // added it to avoid ArgumentNullException inside GetOrAdd if Credentials == null

private readonly ConcurrentDictionary<Credentials, Lazy<Data>> Cache = 
             new ConcurrentDictionary<Credentials, Lazy<Data>>();

public Data GetData(Credentials credential)
{
    Lazy<Data> data = new Lazy<Data>(() => GetDataInternal(credential));
    Lazy<Data> lazyData = Cache.GetOrAdd(credential ?? EmptyCredentials, data);

    bool isAdded = ReferenceEquals(data, lazyData); 

    try
    {
       return lazyData.Value;
    }
    finally
    {
       if (isAdded)
       {
            Cache.TryRemove(credential ?? EmptyCredentials, out lazyData);
        }
    }
}

我添加了finally 块,因为我需要更新我的字典(保持最新)。只有创建缓存值的线程才被允许删除它,以防止竞争。

但我想停止使用ConccurentDictionary 和finally 块,而不是使用MemoryCache。 MemoryCache 有一个驱逐策略,因此它可以丢弃不再需要的条目或您不再有足够内存的条目。这正是我所需要的。

如何更改以下行

Lazy<Data> lazyData = Cache.GetOrAdd(credential ?? EmptyCredentials, data);

通过使用 MemoryCache?

Lazy<Data> lazyData = (Lazy<Data>)MemoryCache.Default.AddOrGetExisting(..., data, 
                                                                    new CacheItemPolicy());

那么,我怎样才能得到我的键值呢?

【问题讨论】:

    标签: c# dictionary memorycache


    【解决方案1】:

    看看下面的解决方案,但我不确定它是否正确

    public Data GetData(Credentials credential)
    {
       var data = new Lazy<Data>(() => GetCurrentInternal(credential));
       var lazydata  = (Lazy<Data>)MemoryCache.Default.AddOrGetExisting(
                       (credential ?? EmptyMetadataCredentials).ToString(),
                        data,
                        DateTime.Now.AddMinutes(5));
    
        return (lazydata ?? data).Value;
    }
    

    【讨论】:

      猜你喜欢
      • 2010-12-02
      • 1970-01-01
      • 1970-01-01
      • 2018-02-25
      • 1970-01-01
      • 2011-05-30
      • 2011-11-24
      • 1970-01-01
      • 2016-10-25
      相关资源
      最近更新 更多