在我的应用程序中,我使用通用处理程序来处理请求。如何将数据表存储在缓存中以重用它?
我想要的机制,如果第一次请求来到处理程序,它向服务器发出请求,然后缓存整个数据表,所以对于即将到来的请求,如果下一个请求的产品代码存在于缓存的数据表中,它不应该去到服务器再次获取数据。它应该只检查数据表的数据。
那么你能解释我如何设置缓存中的数据表。
在我的应用程序中,我使用通用处理程序来处理请求。如何将数据表存储在缓存中以重用它?
我想要的机制,如果第一次请求来到处理程序,它向服务器发出请求,然后缓存整个数据表,所以对于即将到来的请求,如果下一个请求的产品代码存在于缓存的数据表中,它不应该去到服务器再次获取数据。它应该只检查数据表的数据。
那么你能解释我如何设置缓存中的数据表。
东西沿着这些路线?
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;
}
如果数据表发生变化,您将需要某种机制将数据表从缓存中清除。例如,您可以使用SqlCacheDependency。
按照要求,清除缓存小时表添加后,你会怎么做:
HttpContext.Current.Cache.Insert("secret key", dataTable, null, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration);
你可以使用:
HttpContext.Current.Cache["CacheDataTableID"] = datatableInstance;
试试这个
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];
}
,你可以写你的表中的属性像
public DataTable CachedTable { get{
if(Cache["CachedTable"] == null)
{
Cache["CachedTable"]= //get from databse
}
return Cache["CachedTable"];
} }
非线程安全......如果在“if”和“return”之间删除缓存条目会怎么样? –
@Thomas Levesque - 这是不太可能的。 – JonH
@JonH,不可能发生的事情总是发生......如果可能发生,它可能迟早会出现(这大致就是墨菲定律背后的想法) –