在asp.net中,如何在构建新缓存的同时提供旧缓存
本文关键字:缓存 net asp 构建 新缓存 | 更新日期: 2023-09-27 18:24:55
通常在缓存超时后,缓存会被清空,下一个请求会再次建立缓存,导致响应时间变化很大。在asp.net(我使用的是4.0)中,在构建新缓存时,为旧缓存提供服务的最佳方式是什么?
我正在使用HttpRuntime.Cache
我找到了一个似乎工作得很好的解决方案。它基于网站上的另一个答案
public class InMemoryCache : ICacheService
{
public T Get<T>(string key, DateTime? expirationTime, Func<T> fetchDataCallback) where T : class
{
T item = HttpRuntime.Cache.Get(key) as T;
if (item == null)
{
item = fetchDataCallback();
HttpRuntime.Cache.Insert(key, item, null, expirationTime ?? DateTime.Now.AddMinutes(10), TimeSpan.Zero, CacheItemPriority.Normal, (
s, value, reason) =>
{
// recache old data so that users are receiving old cache while the new data is being fetched
HttpRuntime.Cache.Insert(key, value, null, DateTime.Now.AddMinutes(10), TimeSpan.Zero, CacheItemPriority.Normal, null);
// fetch data async and insert into cache again
Task.Factory.StartNew(() => HttpRuntime.Cache.Insert(key, fetchDataCallback(), null, expirationTime ?? DateTime.Now.AddMinutes(10), TimeSpan.Zero, CacheItemPriority.Normal, null));
});
}
return item;
}
}