Attach listener to MemoryCache which can remove expired items

619 Views Asked by At

I am using MemoryCache in one of my project to cache some keys and value. I have attached 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.

I read about MemoryCache and looks like I can use RegisterPostEvictionCallback as shown below:

private static readonly HashSet<string> CacheKeys = new HashSet<string>();

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)
    };
    // attaching listener
    options.RegisterPostEvictionCallback(callback: EvictionCallback, state: this);
    
    if (otherOptions != null) otherOptions(options);

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

    return true;
}

private void EvictionCallback(object key, object value, EvictionReason reason, object state)
{
    CacheKeys.Remove(key);
    var message = $"Entry was evicted. Reason: {reason}.";
    Console.WriteLine(message);
}

It looks like there is some issue where items doesn't expire automatically as per this this thread.

So to avoid the issue mentioned in that thread. Do I need to remove AbsoluteExpirationRelativeToNow and use CancellationTokenSource here?

If yes, how should I go ahead and make the change since I don't want to change the current functionality that I have already in my original code so if I remove AbsoluteExpirationRelativeToNow and use CancellationTokenSource here will it behave differently than what my original code is doing?

0

There are 0 best solutions below