The main reason for low performance in the application is unwanted hits to the server. Caching helps in improving the performance and scalability of the application.
The static content/ data which will not change frequently can be kept in cache. The .Net framework enables to store data in memory for rapid access by using caching. The data will be retrieved from the server for the first time and stored in cache memory, so that when the same data is accessed again, it will be served from cache. The caching can be implemented on client and server side.
Let us see an example of implementing the server caching.
- public static class CacheHandler
- {
- public static void Add < T > (T objInfo, string key)
- {
- HttpContext.Current.Cache.Insert(key, objInfo, null, DateTime.Now.AddMinutes(1440), System.Web.Caching.Cache.NoSlidingExpiration);
- }
- public static void Clear(string key)
- {
- HttpContext.Current.Cache.Remove(key);
- }
- public static bool Exists(string key)
- {
- return HttpContext.Current.Cache[key] != null;
- }
- public static bool Get < T > (string key, out T value)
- {
- try
- {
- if (!Exists(key))
- {
- value =
- default (T);
- return false;
- }
- value = (T) HttpContext.Current.Cache[key];
- }
- catch
- {
- value =
- default (T);
- return false;
- }
- return true;
- }
- }
The above static class has 4 static methods, Add method:
- public static void Add < T > (T objInfo, string key)
- {
- HttpContext.Current.Cache.Insert(key, objInfo, null, DateTime.Now.AddMinutes(1440), System.Web.Caching.Cache.NoSlidingExpiration);
- }
The add method gets the input of generic type and key. It will insert the Cache in the HttpContext.Current.Cache using key and time to expiry is added in minutes.
Exists Method:
- public static bool Exists(string key)
- {
- return HttpContext.Current.Cache[key] != null;
- }
The Exists method checks whether the key is present in the current http context. This method will be used whenever we try to get the cache or to check whether any data available for the key.
Clear Method:
- public static void Clear(string key)
- {
- HttpContext.Current.Cache.Remove(key);
- }
The clear method can removes the cache of corresponding key passed to it.
Get Method :
- public static bool Get < T > (string key, out T value)
- {
- try
- {
- if (!Exists(key))
- {
- value =
- default (T);
- return false;
- }
- value = (T) HttpContext.Current.Cache[key];
- }
- catch
- {
- value =
- default (T);
- return false;
- }
- return true;
- }
The get method retrieves the data from cache for the key passed to it and returns a bool of true and object of T as an output parameter is returned. If the key doesn’t exist in cache default values of object of type is returned as output parameter with false as a return value.
The above class can be used wherever the server caching is needed.