How to store datatable in cache to reuse it?

。_饼干妹妹 提交于 2019-12-17 09:32:23

问题


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.??


回答1:


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);



回答2:


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];
  }



回答3:


you can use:

HttpContext.Current.Cache["CacheDataTableID"] = datatableInstance;



回答4:


you can write a property for your table like

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


来源:https://stackoverflow.com/questions/6831665/how-to-store-datatable-in-cache-to-reuse-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!