【发布时间】:2015-04-01 18:30:03
【问题描述】:
我有一个字典(并发),用于将一个对象 id 映射到另一个。根据输入键获取值 id 相当昂贵,因此我想将字典保存在服务器缓存中。
我第一次尝试了一种方法来做到这一点,但它只是“感觉”可能有更好的方法来做到这一点:
private string GetItem(string cacheKey, string itemKey)
{
string sfAccountId = null;
ConcurrentDictionary<string, string> sfAccountMap =
Context.Cache[cacheKey] as ConcurrentDictionary<string, string>;
if(sfAccountMap == null)
{
lock(cacheLock)
{
sfAccountMap = Context.Cache[cacheKey] as ConcurrentDictionary<string, string>;
if(sfAccountMap == null)
{
sfAccountMap = new ConcurrentDictionary<string, string>();
sfAccountId = ExpensiveMethodReturnsString();
if(!String.IsNullOrEmpty(sfAccountId))
{
sfAccountMap.TryAdd(itemKey, sfAccountId);
}
Context.Cache[cacheKey] = sfAccountMap;
}
}
}
else
{
if(sfAccountMap.ContainsKey(itemKey))
{
sfAccountMap.TryGetValue(itemKey, out sfAccountId);
}
else
{
sfAccountMap.TryAdd(itemKey, ExpensiveMethodReturnsString());
lock(cacheLock)
{
Context.Cache[cacheKey] = sfAccountMap;
}
}
}
return sfAccountId;
}
【问题讨论】:
标签: c# asp.net .net concurrency