How to store datatable in cache to reuse it?

后端 未结 4 1831
半阙折子戏
半阙折子戏 2020-12-01 08:34

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 reques

相关标签:
4条回答
  • 2020-12-01 09:06

    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);
    
    0 讨论(0)
  • 2020-12-01 09:12

    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];
      }
    
    0 讨论(0)
  • 2020-12-01 09:23

    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"]; 
        }  }
    
    0 讨论(0)
  • 2020-12-01 09:28

    you can use:

    HttpContext.Current.Cache["CacheDataTableID"] = datatableInstance;
    
    0 讨论(0)
提交回复
热议问题