【问题标题】:Using of Interlocked.CompareExchange使用 Interlocked.CompareExchange
【发布时间】:2012-06-17 00:51:53
【问题描述】:

伙计们,

我希望您评估下面的下一个代码。 如您所见,我使用 Interlocked.CompareExchange,在这种情况下有意义吗? (我不确定,它是否正确)。

我会很高兴任何笔记、cmets 等。

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;
}

谢谢你。

【问题讨论】:

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


    【解决方案1】:

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

     item =  GetItem(cacheKey, getItemCallback);
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-05
      • 2010-12-07
      • 2013-08-23
      • 2015-11-14
      • 2013-03-07
      • 1970-01-01
      • 1970-01-01
      • 2012-10-14
      相关资源
      最近更新 更多