简体   繁体   中英

How to clear MemoryCache in ASP.NET Core?

How to correctly clear IMemoryCache from ASP.NET Core?

I believe this class is missing Clear method, but anyway how to deal with it? In my project I'm caching DocumentRepository's methods for 24 hours where I'm getting lots of rows from database. But sometimes I can change the database, so I want to clear the IMemoryCache as it has got rubbish data.

IMemoryCache indeed lacks a Clear() method, but it's not hard to implement one yourself.

    public class CacheWrapper
    {
        private readonly IMemoryCache _memoryCache;
        private CancellationTokenSource _resetCacheToken = new();

        public CacheWrapper(IMemoryCache memoryCache)
        {
            _memoryCache = memoryCache;
        }

        public void Add(object key, object value, MemoryCacheEntryOptions memoryCacheEntryOptions)
        {
            using var entry = _memoryCache.CreateEntry(key);
            entry.SetOptions(memoryCacheEntryOptions);
            entry.Value = value;

            // add an expiration token that allows us to clear the entire cache with a single method call
            entry.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token));
        }

        public void Clear()
        {
            _resetCacheToken.Cancel(); // this triggers the CancellationChangeToken to expire every item from cache

            _resetCacheToken.Dispose(); // dispose the current cancellation token source and create a new one
            _resetCacheToken = new CancellationTokenSource();
        }
    }

Based on https://docs.microsoft.com/en-us/aspnet/core/performance/caching/memory?view=aspnetcore-3.1#cache-dependencies and https://stackoverflow.com/a/45543023/2078975

There is an easy way to clear it that may not work in all environments, but where it does work, it works well.

If you're getting your IMemoryCache object through dependency injection, there is a good chance you'll actually be receiving a MemoryCache object. MemoryCache does have a method called Compact() that will clear the cache. You can try to cast the object to MemoryCache and, if successful, call Compact .

Example:

string message;
// _memoryCache is of type IMemoryCache and was set via dependency injection.
var    memoryCache = _memoryCache as MemoryCache;
if (memoryCache != null)
{
    memoryCache.Compact(1);
 
    message ="Cache cleared";
 } else {
    message = "Could not cast cache object to MemoryCache. Cache NOT cleared.";
 }

The cache class and interface don't have any methods for clearing neither ones to iterate over the keys, since it's not meant to be a list and in ASP.NET Core applications one usually use IDistributedCache interface as dependency, since it easier allows you to later change from a local memory cache to a distributed cache (such as memd or Redis).

Instead, if you want to invalidate a specific row, you should remove the cached entry via cache.Remove(myKey) .

Of course, this requires you to know the key you want to invalidate. Typically you do that via events. Every time you update an entry in the database, you would fire up an event. This event will be caught by a background service and cause a cache invalidation.

Locally this can be done with any pub/sub library. In distributed scenarios you may want to use pub/sub features of the distributed cache (ie Redis).

In cases of lookup tables (where many values are affected), you can have a service refresh the cache (ie every 5 to 10 minutes via a background task using a scheduling library such as hangfire or quart.net).

Home work Questions

But one question you should ask yourself: Is it really a good idea to cache documents for 24 hours if they change frequently?

Does the loading of a single document takes so much time, that caching it 24 hours will be worth? Or are shorter times good enough (15, 30, 60 minutes)?

要清除 MemoryCache,只需按键删除内存缓存,如下所示:

memoryCache.Remove("your_key");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM