0

I would love to remove all items from MemoryCache.

What I have tried already:

var listDBCalls = ((FixedSizedQueue<DalCacheDto>)MemoryCache.Default.Get($"DAL_CACHE_{HttpContext.Current?.User?.Identity?.Name}"))?.ToList();
listDBCalls.clear();

If I watch this code in debugger, it shows that listDBCalls is really empty. But, calling again:

((FixedSizedQueue<DalCacheDto>)MemoryCache.Default.Get($"DAL_CACHE_{HttpContext.Current?.User?.Identity?.Name}"))?.ToList()

is showing me that all items are still there. Why is that?

FrenkyB
  • 6,625
  • 14
  • 67
  • 114
  • 1
    It's because it creates a list with the element you ask. You can empty the list but the elements still exist in the cache. The list is living independently from the cache even is the objects are shared. – Arcord Jun 20 '20 at 16:38
  • Also be careful with that cache key. All unauthenticated/anonymous users end up with the same key - - that could be an issue depending on how/what you are using it for – pinkfloydx33 Jun 20 '20 at 17:33

1 Answers1

1

Avoid to use the default memory cache to have more control. Create your own memory cache (by example as a static property of a static class) and when you need to erased it you can simply create a new one to replace the older one. Don't forget to call the dispose method.

It seems the way to go : How to clear MemoryCache?

Edit When I read you code I'm not sure what you want to do. If you want to remove a particular entry (which seems the case) you can use the remove method.

MemoryCache.Default.Remove($"DAL_CACHE_{HttpContext.Current?.User?.Identity?.Name}")
Arcord
  • 1,724
  • 1
  • 11
  • 16