ASP.net cache is great feature through which we can increase the performance of the our web application via reducing server round trips to database. We can cache any serializable data into the cache. There are so many ways to cache data but one of the simplest way to cache data like insert data into cache object. Here we must need to validate cache if any data is changed and there are so many ways from where we can set dependency to validate the cache like files,SQL Cache Dependency etc. We also can validate cache or expire via setting time to duration to its object. Like after the defined time our cache will expire and then it will again put new fresh data into the cache. This is called as time base expiration. We can put this kind of expiration via two way.
- Absolute Expiration
- Sliding Expiration
Absolute Expiration: Absolute expiration means It will expire cache after some time period set at the time of activating cache. This will be absolute expiration whether cache will be used or not It will expire the cache. This type of expiration used to cache data which are not frequently changing.
Sliding Expiration: Sliding expiration means It will expire cache after time period at the time of activating cache if any request is not made during this time period. This type of expiration is useful when there are so many data to cache. So It will put those items in the cache which are frequently used in the application. So it will not going to use unnecessary memory.
Here is the example how we can set the sliding expiration and absolute expiration.
string cacheData = "The data to be cached"; //Absolute Expiration Cache.Insert("AbsoluteCacheKey", cacheData, null, DateTime.Now.AddMinutes(1), System.Web.Caching.Cache.NoSlidingExpiration); //Sliding Expiration Cache.Insert("SlidingExpiration", cacheData, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(1));In above example I have created the a string to be cache that can be any serialized data. In the absolute expiration you can see that it will expires after one minute whether its accessed or not. While in sliding expiration it will expire cache if cache is not accessed within specified time.
Hope this will help you for better understanding of asp.net caching technique. Happy programming!!!