【发布时间】: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