Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store datatable in cache to reuse it?

In my application i have used Generic handler to serve requests.

I want mechanism like if the first time request comes to handler ,it makes a request to server and then Cache whole datatable, so for upcoming request if the next requested productcode is exist in the datatable of cache, it should not go to server for fetching data again..it should check data of datatable only.

So can you explain me how can i set datatable in cache.??

like image 953
Kishan Gajjar Avatar asked Jul 26 '11 14:07

Kishan Gajjar


3 Answers

Something along these lines?

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're going to need some mechanism to flush the data table from the cache if it changes. For example you could use an SqlCacheDependency.

As requested, to clear the cache an hour after the table is added you would do:

HttpContext.Current.Cache.Insert("secret key", dataTable, null, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration);
like image 148
James Gaunt Avatar answered Sep 24 '22 15:09

James Gaunt


try this

 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];
  }
like image 40
Amir Ismail Avatar answered Sep 21 '22 15:09

Amir Ismail


you can use:

HttpContext.Current.Cache["CacheDataTableID"] = datatableInstance;
like image 34
Antonio Bakula Avatar answered Sep 23 '22 15:09

Antonio Bakula