.Net MemoryCache - Absolute expiration vs sliding expiration

So you are going to use MemoryCache and you have to choose a way to expire your cache. Here I will give you your two options: Absolute expiration and sliding expiration.

Absolute Expiration

Absolute expiration expires the cacheitem when the given time has been reached. Giving it a datetime (or datetimeoffset) in the future it 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);

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);