Asp.net 使缓存过期的最佳方法
以下是我检索所有类别的代码,它运行良好:Asp.net 使缓存过期的最佳方法,asp.net,caching,global-asax,Asp.net,Caching,Global Asax,以下是我检索所有类别的代码,它运行良好: public static List<Category> GetAllCategories() { var context = HttpContext.Current; var profiler = MiniProfiler.Current; using (profiler.Step("GetAllCategories()")) { if (context.Cache["StoreCategor
public static List<Category> GetAllCategories()
{
var context = HttpContext.Current;
var profiler = MiniProfiler.Current;
using (profiler.Step("GetAllCategories()"))
{
if (context.Cache["StoreCategories"] == null)
{
var r = new List<Category>();
using (var db = new MainContext())
{
var q = db.v2StoreCategories;
foreach (var cat in q)
{
r.Add(new Category(cat));
}
}
context.Cache["StoreCategories"] = r;
}
}
return (List<Category>)HttpContext.Current.Cache["StoreCategories"];
}
假设我需要以每n分钟刷新一次缓存的方式进行构建,那么最好的方法是什么
在global.asax中设置定时事件是否安全?使用类似
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
如适用
确保使用正确的上下文。即
HttpContext.Current
我建议你使用缓存。插入。。。方法这样,您就可以为缓存中的对象提供生存时间。大概是这样的:
public static List<Category> GetAllCategories()
{
var context = HttpContext.Current;
var profiler = MiniProfiler.Current;
using (profiler.Step("GetAllCategories()"))
{
if (context.Cache["StoreCategories"] == null)
{
var r = new List<Category>();
using (var db = new MainContext())
{
var q = db.v2StoreCategories;
foreach (var cat in q)
{
r.Add(new Category(cat));
}
}
HttpContext.Current.Cache.Insert(
"StoreCategories",
r,
null,
DateTime.UtcNow.AddMinutes(1), // TTL = one minute in this sample
TimeSpan.Zero
);
}
}
return (List<Category>)HttpContext.Current.Cache["StoreCategories"];
}
以及:
HttpContext.Current.Cache.Insert(
"StoreCategories",
r,
null,
DateTime.UtcNow.AddMinutes(1),
TimeSpan.Zero,
UpdateCategoriesCache
);
private static void UpdateCategoriesCache(
string key,
System.Web.Caching.CacheItemUpdateReason reason,
out Object categories,
out CacheDependency dependency,
out DateTime absoluteExpiration,
out TimeSpan slidingExpiration
)
{
// fetch categories here
categories = fetchedCategories;
dependency = null;
absoluteExpiration = DateTime.UtcNow.AddMinutes(1);
slidingExpiration = TimeSpan.Zero;
}