Question

guys,

I would like to you evaluate next code below. As you see, I use Interlocked.CompareExchange, does it make sense in this context? (I am not sure, that it is correct).

I'll be glad any notes, comments, etc.

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

Thank you advance.

Was it helpful?

Solution

No it does not make sense to use CompareExchange in this particular case - local variables are accessible from the current thread only as is. That line could be replaced with:

 item =  GetItem(cacheKey, getItemCallback);

I would consider using CompareExchange() to access a field inside a class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top