Skip to main content
 首页 » 编程设计

c#之使用 Interlocked.CompareExchange

2024年02月20日1598°冷暖

伙计们,

我希望您评估下面的下一个代码。 如您所见,我使用 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; 
} 

提前致谢。

请您参考如下方法:

不,在这种特殊情况下使用 CompareExchange 没有意义 - 局部变量只能从当前线程按原样访问。该行可以替换为:

 item =  GetItem(cacheKey, getItemCallback); 

我会考虑使用 CompareExchange() 来访问类中的字段。