Generic Caching
Using caching combined with the generic type and used to handle all system types and custom types of a class e.g. we can handle any custom object like Int, String, Class etc.
Use of Caching
- Increase the performance of the web application.
- Reduce server round trips to database.
- Cache any serializable data or object data into the cache.
- Very fast and flexible.
- Able to set expire time.
- Also able to refresh new data.
- Can place any time of object like Dictionary<T, K>, List<T>, custom class etc.
- Also can place system defined type like String, Date, Time etc.
Used Terms
- AbsoluteExpiration: The time at which the inserted object expires and is removed from the cache.
- SlidingExpiration: The interval between the time the inserted object is last accessed and when that object expires. If this value is the equivalent of 20 minutes, the object will expire and be removed from the cache 20 minutes after it was last accessed.
Used Namespace
using System;
using System.Web;
using System.Web.Caching;
Used Concept
HttpRuntime.Cache
Usage of Absolute Expiration
//This is for Absolute Expiration
string strCache = GenericCustomCache.GetItemToCache<string>("String", "Good Moring!", DateTime.Now.AddSeconds(20));
DateTime dtCache = GenericCustomCache.GetItemToCache<DateTime>("DT", DateTime.Now, DateTime.Now.AddSeconds(20));
Response.Write("Absolute Expiration<br/>");
Response.Write(strCache + dtCache.ToString() + "<br/>");
Usage of Sliding Expiration
//This is for Sliding Expiration
string strCache1 = GenericCustomCache.GetItemToCache<string>("String1", "Good Moring!", TimeSpan.FromSeconds(20));
DateTime dtCache1 = GenericCustomCache.GetItemToCache<DateTime>("DT1", DateTime.Now, TimeSpan.FromSeconds(20));
Response.Write("Sliding Expiration<br/>");
Response.Write(strCache1 + dtCache1.ToString() + "<br/>");
Method for Absolute Expiration
/// <summary>
/// This is used to get item from cache using absoluteExpiration.
/// </summary>
internal static T GetItemToCache<T>(string key, object cacheObject, DateTime absoluteExpiration)
{
return GetItemToCache<T>(key, cacheObject, absoluteExpiration, Cache.NoSlidingExpiration);
}
Method for Sliding Expiration
/// <summary>
/// This is used to get item from cache using absoluteExpiration.
/// </summary>
internal static T GetItemToCache<T>(string key, object cacheObject, TimeSpan slidingExpiration)
{
return GetItemToCache<T>(key, cacheObject, Cache.NoAbsoluteExpiration, slidingExpiration);
}
Note: Download the source code attached which gives the custom generic cache class to verify the activity of caching.
Also the source code has been written for reuse. So you just use the generic custom class in your application directly for any type of data.
Thanks for reading this article. Have a nice day.