在asp.net中,如何在构建新缓存时提供旧缓存?

时间:2013-07-25 08:01:31

标签: c# asp.net caching

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

我正在使用HttpRuntime.Cache

1 个答案:

答案 0 :(得分:1)

我找到了一个似乎很好用的解决方案。它基于另一个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;
    }
}