0
通常在高速緩存超時後,高速緩存將被清空,並且下一個請求會再次構建高速緩存,從而導致響應時間非常可變。在asp.net中(我正在使用4.0)在新的緩存建立時服務舊緩存的最佳方式是什麼?在asp.net中,如何在構建新緩存時提供舊緩存?
我使用HttpRuntime.Cache
通常在高速緩存超時後,高速緩存將被清空,並且下一個請求會再次構建高速緩存,從而導致響應時間非常可變。在asp.net中(我正在使用4.0)在新的緩存建立時服務舊緩存的最佳方式是什麼?在asp.net中,如何在構建新緩存時提供舊緩存?
我使用HttpRuntime.Cache
我發現,似乎很好地工作的解決方案。它基於另一個answer here on the site
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;
}
}