Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace LongCacheTest
- {
- public class Program
- {
- public static void Main(string[] args)
- {
- var cacher = new Cacher.Cacher<string>();
- cacher.Add("first", SimulateSlowLoadingContentRetrieval);
- cacher.Add("second", SimulateSlowLoadingContentRetrieval);
- Console.ReadLine();
- }
- private static string SimulateSlowLoadingContentRetrieval(string key)
- {
- var end = DateTime.Now.AddSeconds(10);
- while (DateTime.Now < end) ;
- return $"content:{key}";
- }
- }
- }
- using System;
- using System.Runtime.Caching;
- using System.Threading.Tasks;
- namespace Cacher
- {
- public class Cacher<T>
- {
- public delegate T CacheEntryGet(string key);
- private MemoryCache Cache { get; set; } = new MemoryCache("long");
- private CacheItemPolicy ImmediatePolicy => new CacheItemPolicy
- {
- AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(3)),
- Priority = CacheItemPriority.Default,
- RemovedCallback = DidRemove
- };
- private CacheItemPolicy RegularPolicy => new CacheItemPolicy
- {
- AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(20)),
- Priority = CacheItemPriority.Default,
- RemovedCallback = DidRemove
- };
- private CacheItemPolicy NoRemovePolicy => new CacheItemPolicy
- {
- Priority = CacheItemPriority.NotRemovable
- };
- private async Task GetFreshContent(CacheEntryRemovedArguments args)
- {
- await Task.Run(() =>
- {
- Cache.Set(args.CacheItem, NoRemovePolicy);
- var item = args.CacheItem.Value as Cacheable<T>;
- item.Obj = item.Getter(args.CacheItem.Key);
- var policy = RegularPolicy;
- Cache.Set(args.CacheItem, policy);
- });
- }
- private void DidRemove(CacheEntryRemovedArguments args)
- {
- GetFreshContent(args);
- }
- public void Add(string key, CacheEntryGet getter)
- {
- var item = new Cacheable<T>
- {
- Getter = getter
- };
- Cache.Set(key, item, ImmediatePolicy);
- }
- public T Get(string key) => (Cache[key] as Cacheable<T>).Obj;
- }
- }
Add Comment
Please, Sign In to add comment