Clear Or Reset Cache In .Net Core

Mahdi Elahi 31 Reputation points
2022-03-31T10:59:24.74+00:00

Hi,
i set permissions users in cache with imemory cache,

  1. but how to reset or clear cache ?
    i use Dispose() but i have this error
    188752-capture.png
  2. maybe i have many cache keys that name's contains permission-{userId} can i remove cache key that names contains permission-..... (any text)?
Developer technologies ASP.NET ASP.NET Core
{count} votes

2 answers

Sort by: Most helpful
  1. Anonymous
    2022-04-01T04:51:48.573+00:00

    Hi @Mahdi Elahi ,

    but how to reset or clear cache ?

    To reset the cache entry, first you could get the exist cache entry (use the TryGetValue method), then use the Set Method to reset the value. Like this:

    if (!_memoryCache.TryGetValue(CacheKeys.Entry, out DateTime cacheValue))  
    {  
        cacheValue = CurrentDateTime;  
    
        var cacheEntryOptions = new MemoryCacheEntryOptions()  
            .SetSlidingExpiration(TimeSpan.FromSeconds(3));  
    
        _memoryCache.Set(CacheKeys.Entry, cacheValue, cacheEntryOptions);  
    }   
    

    To clear the cache entry, you could use the Compact or Remove method, like this:

    _myMemoryCache.Cache.Remove(CacheKeys.Entry);  
    _myMemoryCache.Cache.Compact(.25);  
    

    Note: MemoryCache.Compact attempts to remove the specified percentage of the cache in the following order:

    • All expired items.
    • Items by priority. Lowest priority items are removed first.
    • Least recently used objects.
    • Items with the earliest absolute expiration.
    • Items with the earliest sliding expiration.

    Pinned items with priority NeverRemove are never removed. The above code removes a cache item and calls Compact to remove 25% of cached entries.

    More detail information, see Cache in-memory in ASP.NET Core

    maybe i have many cache keys that name's contains permission-{userId}
    can i remove cache key that names contains permission-..... (any text)?

    From the Microsoft.Extensions.Caching.Memory.MemoryCache source data, we can see it does not expose any members allowing to retrieve all cache keys, so we can't retrieve all cache keys from the memory cache.

    So for the above issue, you might need to store the cache keys somewhere (as a list), then you can use the LINQ query statement to filter the keys, and then use the Remove method to remove the filtered cache entry.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments

  2. Silvair L. Soares 1 Reputation point
    2022-08-26T13:56:40.753+00:00

    It is not a vague requirement. It's too objective. How to remove all cached entries?

    @Mahdi Elahi , use this code example:

    using System.Collections.Generic;  
    using Microsoft.Extensions.Caching.Memory;  
    using ServiceStack;  
    
    public static class IMemoryCacheExtensions  
    {  
        static readonly List<object> entries = new();  
      
        /// <summary>  
        /// Removes all entries, added via the "TryGetValueExtension()" method  
        /// </summary>  
        /// <param name="cache"></param>  
        public static void Clear(this IMemoryCache cache)  
        {  
            for (int i = 0; i < entries.Count; i++)  
            {  
                cache.Remove(entries[i]);  
            }  
            entries.Clear();  
        }  
      
        /// <summary>  
        /// Use this extension method, to be able to remove all your entries later using "Clear()" method  
        /// </summary>  
        /// <typeparam name="TItem"></typeparam>  
        /// <param name="cache"></param>  
        /// <param name="key"></param>  
        /// <param name="value"></param>  
        /// <returns></returns>  
        public static bool TryGetValueExtension<TItem>(this IMemoryCache cache, object key, out TItem value)  
        {  
            entries.AddIfNotExists(key);  
      
            if (cache.TryGetValue(key, out object result))  
            {  
                if (result == null)  
                {  
                    value = default;  
                    return true;  
                }  
      
                if (result is TItem item)  
                {  
                    value = item;  
                    return true;  
                }  
            }  
      
            value = default;  
            return false;  
        }  
    }  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.