How to attach a listener to MemoryCache which gets called on expiration of keys?

1.8k Views Asked by At

I am using MemoryCache in one of my project to cache some keys and value.

private bool CacheEntries<T>(MemoryCache memoryCache, string cacheKey, T value, Configuration config, Action<MemoryCacheEntryOptions> otherOptions = null)
{
    int minutes = randomGenerator.Next(config.LowTime, config.HighTime);

    MemoryCacheEntryOptions options = new MemoryCacheEntryOptions()
    {
        Size = config.Size,
        Priority = config.Priority,
        AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(minutes)
    };

    if (otherOptions != null) otherOptions(options);

    CacheKeys.Add(cacheKey);
    memoryCache.Set<T>(cacheKey, value, options);

    return true;
}

I have an expiration on my keys as shown above. Also I am storing same key in CacheKeys HashSet data structure for later use. Is there any way to attach a listener on my MemoryCache that whenever it is expiring any items then that listener should get called so that I can remove those keys from CacheKeys HashSet as well. Basically I want to be consistent with what I have in CacheKeys and MemoryCache.

Is this possible to do?

1

There are 1 best solutions below

0
On BEST ANSWER

You appear to be using the Platform Extensions object from Microsoft.Extensions.Caching.Memory. You can use the MemoryCacheEntryOptions.PostEvictionCallbacks property for the MemoryCacheEntryOptions object when you set the item's value in the cache:

Gets or sets the callbacks will be fired after the cache entry is evicted from the cache.

Alternatively, if you can change to the System.Runtime.Caching version of MemoryCache, you can use the CacheItemPolicy when setting the value. From the documentation:

A CacheItemPolicy instance contains information that can be associated with a cache entry. For example, when a cache entry is about to be removed from the cache, a CacheEntryUpdateArguments object is passed to a callback method. The UpdatedCacheItemPolicy property of the CacheEntryUpdateArguments object can pass a reference to a CacheItemPolicy instance that can include eviction and expiration details about the cache entry.

Another alternative with that version of MemoryCache is to call CreateCacheEntryChangeMonitor:

The CreateCacheEntryChangeMonitor method creates a CacheEntryChangeMonitor instance. This specialized change monitor is used to monitor the cache entries that are specified in the keys collection and to trigger events when the entries change.

A monitored entry is considered to have changed for any of the following reasons:

  • The key does not exist at the time of the call to the CreateCacheEntryChangeMonitor method. In that case, the resulting CacheEntryChangeMonitor instance is immediately set to a changed state. This means that when code subsequently binds a change-notification callback, the callback is triggered immediately.

  • The associated cache entry was removed from the cache. This can occur if the entry is explicitly removed, if it expires, or if it is evicted to recover memory