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