Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MemoryCache with certain number of items

Tags:

c#

caching

does MemoryCache has functionality to cache fixed number of items?

e.g. We are only interested in cache 2000 items from database. While keep adding items to the cache, if the specified number of items are exceeded, the oldest one can be removed.

If not, do we have to use another thread to do the house keeping regularly?

like image 213
user1604006 Avatar asked Feb 19 '23 05:02

user1604006


1 Answers

It doesn't have anything built in that will limit the number of objects. Instead, it checks how much memory is being used, and compares it to the CacheMemoryLimit. If the CacheMemoryLimit is exceeded, it will drop older items. You can also set items to automatically expire after a certain amount of time via the CacheItemPolicy.

These approaches both make more sense if you're really using it as a Memory Cache. In other words, if you're worried about the tradeoff between a memory limit and the cost of fetching data, these are great ways to determine when to evict items from the cache. So ask yourself:

Am I really trying to use this as a MemoryCache? Why do I even care if only 2000 items are loaded from the database?

If you are worried about the memory overhead, or if you are worried about the items getting out of date, there are other (better) ways to manage the cache than specifying a number of objects. If you've got some custom reason to keep a specific number of objects in a data structure, consider using a different class.

like image 168
StriplingWarrior Avatar answered Feb 27 '23 03:02

StriplingWarrior