Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to purge expired items from cache?

Tags:

c#

.net

caching

I've got a nice little class built that acts as a cache. Each item has an expiration TimeSpan or DateTime. Each time an attempt to access an item in the cache is made, the item's expiration is checked, and if it's expired, the item is removed from the cache and nothing is returned.

That's great for objects that are accessed frequently, but if an item is put in the cache and never accessed again, it's never removed, even though it's expired.

What's a good methodology for expiring such items from the cache?

Should I have a background thread infinitely enumerating every item in the cache to check if it's expired?

like image 326
core Avatar asked Nov 17 '25 21:11

core


1 Answers

The best code is no code. Use the ASP.NET cache instead. You can reference it as System.Web.HttpRuntime.Cache in any application, not just web applications.

like image 199
Joe Avatar answered Nov 20 '25 12:11

Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!