Base solution for your next web application
Starts in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

ICache AddOrUpdate #8115


User avatar
0
abarref created

The ICache only has Get and Set separately. Must I handle concurrency by myself or there is some extension method similar to ConcurrentDictionary.AddOrUpdate? Thanks in advance


2 Answer(s)
  • User Avatar
    0
    maliming created
    Support Team

    CacheBase internal methods use locks.

    https://github.com/aspnetboilerplate/aspnetboilerplate/blob/13cd661087b92cc0ec3ea08ce3b174d3759728a8/src/Abp/Runtime/Caching/CacheBase.cs#L55

  • User Avatar
    0
    abarref created

    Yes, I saw that. I was wondering if there was something similar to the AddOrUpdate method of ConcurrentDictionary. I ended up writing the following extension method:

    public static class CacheExtensions
    {
        public static TValue GetOrUpdate<TKey, TValue>(this ICache cache, TKey key, Func<TValue> seedFactory, Func<TValue, TValue> updateFactory)
        {
            lock (cache)
            {
                var value = cache.Get(key, k => seedFactory());
    
                value = updateFactory(value);
    
                cache.Set(key.ToString(), value);
    
                return value;
            }
        }
    }