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;
- }
- }
- Add
- Clear
- Exists
- Get
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);
- }
Exists Method:
- public static bool Exists(string key)
- {
- return HttpContext.Current.Cache[key] != null;
- }
Clear Method:
- public static void Clear(string key)
- {
- HttpContext.Current.Cache.Remove(key);
- }
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 above class can be used wherever the server caching is needed.

rukshan pokhrelPosted Dec 19, 2019, 5:47 AM
How to add a cache item from another class ?? the cacheHandler class is static so it cannot be instantiated... how do i call the add method from my controller class? ... Also how can i use the onRemoveCallBack method on this class? i need to update my database when the cache expires..
Manas MohapatraPosted Jan 3, 2016, 6:06 AM
It implemented in generic. Useful one.