Automatically re-populate the cache upon expiration

I am currently caching the result of a method call.

The caching code follows standard templates: it uses an element in the cache, if it exists, otherwise it calculates the result, caching it for future calls, before returning it.

I would like to protect client code from cache skips (for example, when an item has expired).

I am thinking of creating a thread to wait for the life of the cached object, and then running the provided function to refill the cache when (or only earlier) the existing item expires.

Can anyone share experiences related to this? Does that sound like a reasonable approach?

I am using .NET 4.0.

+3
source share
4 answers

Since this is ASP.NET, the method Cache.Insert()allows you to specify a delegate callback.

Does that sound like a reasonable approach?

Yes, a callback (and file dependency) is provided for such a situation. You still have a trade between resources, latency and uncertainty.

+4
source

A new addition to the .NET Framework 4.0 is the MemoryCache Class

Quote from the Docs:

The MemoryCache class is similar to the ASP.NET cache class. The MemoryCache class has many properties, and you will be familiar with cache access methods if you used the ASP.NET cache class.

You can use the AddOrGetExisting method to get or create a CacheItem if it does not exist.

+4
source

, :

var cache = new ConcurrentDictionary<TKey, TValue>();

var value = cache.GetOrAdd(someKey, key => MyMethod(key));

?


, :

var cache = new ConcurrentDictionary<TKey, Tuple<TValue, DateTime>>();

var value = cache.AddOrUpdate(someKey,
             key => Tuple.Create(MyMethod(key), DateTime.Now),
    (key, value) => (value.Item2 + lifetime < DateTime.Now)
                  ? Tuple.Create(MyMethod(key), DateTime.Now)
                  : value)
                  .Item1;

?

+2

It seems that it makes no sense to stop the object in order to immediately recreate it. Just turn off the expiration; dtb shows how.

0
source

Source: https://habr.com/ru/post/1764730/


All Articles