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);
James gaunt
source share