伙计们,
我想让你评估下面的代码。如您所见,我使用的是Interlocked.CompareExchange,它在这个上下文中有意义吗?(我不确定它是否正确)。
我很高兴有任何笔记,评论,等等。
private static T GetItem<T>(string cacheKey, Func<T> getItemCallback) where T : class
{
var item = (HttpRuntime.Cache.Get(cacheKey) as T);
if (item != null)
{
return item;
}
item = getItemCallback.Invoke();
if (item != null)
{
HttpContext.Current.Cache.Insert(cacheKey, item);
}
return item;
}
public T Get<T>(string cacheKey, Func<T> getItemCallback) where T : class
{
var item = (HttpRuntime.Cache.Get(cacheKey) as T);
if (item != null)
{
return item;
}
Interlocked.CompareExchange(ref item, GetItem(cacheKey, getItemCallback), null);
return item;
}谢谢你的预支。
发布于 2012-06-17 08:57:02
不,在这种特殊情况下使用CompareExchange没有意义-局部变量只能按原样从当前线程访问。这一行可以替换为:
item = GetItem(cacheKey, getItemCallback);我会考虑使用CompareExchange()来访问类中的字段。
https://stackoverflow.com/questions/11068135
复制相似问题