How to clear expired items from cache?

I have a nice little class that works like a cache. Each item has a TimeSpan or DateTime expiration date. Each time an attempt is made to access an item in the cache, the item expires, and if it expired, the item is deleted from the cache and nothing is returned.

This is great for frequently accessed objects, but if an item is cached and never reopened, it is never deleted, even if it has expired.

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

Do I have to have a background thread endlessly listing every item in the cache to check if it has expired?

+3
source share
5 answers

, , . , . . .Net , .

, . , , -. -, . , .

+1

- . ASP.NET. System.Web.HttpRuntime.Cache , -.

+5

LRU ( ), , , , , , . . .

, , . - , .

+1

You can also make changes to the cache (restart) the timer at intervals set to the closest timestamp of expiration. This will be inaccurate up to a millisecond and depends on the operation of the message pump, but is not very resource intensive.

Harald Sheikh’s answer is better, although if you don’t mind that objects hang forever when the cache is not updated.

+1
source

You can clear selected old items from the cache on first access 1 minute after the last items have been cleared.

private DateTime nextFlush;
public object getItem(object key)
{
  DateTime now = DateTime.Now
  if (now > nextFlush)
  {
    Flush();
    nextFlush = now.AddMinutes(1)
  }
  return fetchItem(key);
}
+1
source

Source: https://habr.com/ru/post/1697587/


All Articles