C# MemoryCache - Absolute expiration vs sliding expiration

So you are going to use MemoryCache and you have to choose a way to expire your cache. There are two options: Absolute expiration and sliding expiration, let us have a look at both!

In short:

  • Absolute Expiration expires items after X amount of time has passed.
  • Sliding Expiration expires items X amount of time after they have last been accessed or were added.

Absolute Expiration

Absolute expiration expires the cacheitem when the given time has been reached. Giving it a datetime (or datetimeoffset) in the future, will expire the item at that point. Absolute expiration is not very precise see this post for more information on that. For Absolute expiration, if you wish to expire the cache 30 minutes (for example) into the future. Then you will have to create a new CacheItemPolicy for each cacheitem (Whereas with Sliding Expiration you can just define one). As the actual time for the expiration has to be set each time. Below is a small example of Absolute expiration.

var cache = MemoryCache.Default;
CacheItemPolicy policy = new CacheItemPolicy
{
   AbsoluteExpiration = DateTimeOffset.UtcNow.AddMinutes(30)
};

cache.Set(new CacheItem("item", new { }), policy);

Using the above the item will expire after 30 minutes.

Sliding expiration

Sliding expiration expires the cacheitem if it has not been accessed within the timespan provided. This makes it easy to keep highly used items in cache. However be careful if you expect something to be refreshed at some point. Items that are used too often may never get expired - and therefore never refreshed. Below is a small example of Sliding Expiration

var cache = MemoryCache.Default;
CacheItemPolicy policy = new CacheItemPolicy
{
   SlidingExpiration = TimeSpan.FromMinutes(30)
};

cache.Set(new CacheItem("item", new { }), policy);

Using the above the item will only expire if not accessed within 30 minutes. Accessing it resets the timer for it to be expired back to 30 minutes.

That is all

Feel free to leave a comment down below if you found this helpful! I read all the comments!