簡體   English   中英

使用Interlocked.CompareExchange

[英]Using of Interlocked.CompareExchange

伙計們,

我想評估下面的代碼。 如您所見,我使用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()來訪問類中的字段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM