How to store data in cache for reuse?

In my application, I used a generic handler to serve requests.

I want the mechanism, as if the first time request came to the handler, it makes a request to the server, and then the entire Cache file, so for the upcoming request, if the next requested product code exists in the data cache, it does not need the server to receive data again .. he should check the data only for the data.

So you can explain to me how I can set datatable to cache.

+7
source share
4 answers

Something like that?

public DataTable GetDataTableFromCacheOrDatabase() { DataTable dataTable = HttpContext.Current.Cache["secret key"] as DataTable; if(dataTable == null) { dataTable = GetDataTableFromDatabase(); HttpContext.Current.Cache["secret key"] = dataTable; } return dataTable; } 

You will need some mechanism to clear the data table from the cache if it changes. For example, you can use SqlCacheDependency .

As requested, to clear the cache one hour after adding the table, follow these steps:

 HttpContext.Current.Cache.Insert("secret key", dataTable, null, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration); 
+23
source

try it

  DataTable mytable; String key = "key" if(HttpContext.Current.Cache[Key] ==null) { mytable = GetDTFromDB(); if(mytable.Rows.Count > 0) HttpContext.Current.Cache.Insert(strKey, mytable, Nothing, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration); else mytable = HttpContext.Current.Cache[strKey]; } 
+4
source

you can use:

 HttpContext.Current.Cache["CacheDataTableID"] = datatableInstance; 
+1
source

you can write a property for your table e.g.

 public DataTable CachedTable { get{ if(Cache["CachedTable"] == null) { Cache["CachedTable"]= //get from databse } return Cache["CachedTable"]; } } 
0
source

All Articles