简体   繁体   English

如何将数据表存储在缓存中以重复使用?

[英]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.?? 所以你能解释一下如何在缓存中设置数据表吗?

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 . 例如,您可以使用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);

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

您可以使用:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM