.Net Core MemoryCache PostEvictionCallback not working properly

To add onto the accept answer and comments, you can force the cache to expire and evict automatically by using a expiring cancellation token.

int expirationMinutes = 60;
var expirationTime = DateTime.Now.Add(expirationMinutes);
var expirationToken = new CancellationChangeToken(
    new CancellationTokenSource(TimeSpan.FromMinutes(expirationMinutes + .01)).Token);

var cacheEntryOptions = new MemoryCacheEntryOptions()
         // Pin to cache.
         .SetPriority(CacheItemPriority.NeverRemove)
         // Set the actual expiration time
         .SetAbsoluteExpiration(expirationTime)
         // Force eviction to run
         .AddExpirationToken(expirationToken)
         // Add eviction callback
         .RegisterPostEvictionCallback(callback: CacheItemRemoved, state: this); 

`

The lack of built in timer behavior, which the old one used to have, is supposed to be by design and this is what was recommended in its place. See: https://github.com/aspnet/Caching/issues/248

Leave a Comment