简体   繁体   中英

In asp.net how can I serve the old cache while building the new one?

Usually after a cache timeout the cache is emptied and the next request will build up the cache again causing very variable response times. In asp.net (I am using 4.0) what is the best way to serve the old cache while the new one is building?

I am using HttpRuntime.Cache

I found a solution that seems to work nicely. Its based on another 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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM