0

通常在缓存超时后缓存被清空,下一个请求将再次建立缓存,从而导致响应时间非常可变。在 asp.net(我使用的是 4.0)中,在构建新缓存时提供旧缓存的最佳方式是什么?

我正在使用 HttpRuntime.Cache

4

1 回答 1

1

我找到了一个似乎效果很好的解决方案。它基于网站上的另一个答案

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;
    }
}
于 2013-07-25T13:21:39.850 回答