使用Interlocked.CompareExchange

时间:2012-06-17 00:51:54

标签: c# asp.net .net multithreading interlocked

人,

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

谢谢你提前。

1 个答案:

答案 0 :(得分:4)

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

 item =  GetItem(cacheKey, getItemCallback);

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

相关问题