Understanding Asp.net Cache Sliding Expiration and Absolute Expiration

Asp .Net provides two different ways to expire the cache on the basis of time. Here are two aproaches:-
  1. Sliding Expiration
  2. Absolute Expiration 
1. Absolute Expiration
Absolute expiration means that your data will be removed from cache after fixed amount of time either it is accessed or not. Generally we use it when we are displaying data which is changing but we can afford to display outdated data in our pages.  Mostly I put all of my dropdown values in cache with Absolute Expiration. Here is how you can code:-
DataTable dt = GetDataFromDatabase();
Cache.Insert("AbsoluteCacheKey", dt, null,
DateTime.Now.AddMinutes(1), //Data will expire after 1 minute
System.Web.Caching.Cache.NoSlidingExpiration);

2. Sliding Expiration
Sliding expiration means that your data will be removed from cache if that is not accessed for certain amount of time. Generally we store that data in this cache mode which is accessed many time on certain occasions. For example if you go in account settings section of a site, then you will be frequently accesing account information in that section. But most of the time you wont be using account setting's related data so there is no point of storing that data in cache. In such scenarios sliding expiration should be used. here is how you can save data in cache with sliding expiration:-

DataTable dt = GetDataFromDatabase();

Cache.Insert("SlidingExpiration", data, null,

System.Web.Caching.Cache.NoAbsoluteExpiration,

TimeSpan.FromMinutes(1));//Data will be cached for 1 mins


Hopefully this information will be useful for you, feel free to share your feedback with me. Happy Coding !!!