Guest User

Untitled

a guest
Jan 24th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. using System;
  2.  
  3. namespace LongCacheTest
  4. {
  5. public class Program
  6. {
  7. public static void Main(string[] args)
  8. {
  9. var cacher = new Cacher.Cacher<string>();
  10.  
  11. cacher.Add("first", SimulateSlowLoadingContentRetrieval);
  12. cacher.Add("second", SimulateSlowLoadingContentRetrieval);
  13.  
  14. Console.ReadLine();
  15. }
  16.  
  17. private static string SimulateSlowLoadingContentRetrieval(string key)
  18. {
  19. var end = DateTime.Now.AddSeconds(10);
  20.  
  21. while (DateTime.Now < end) ;
  22.  
  23. return $"content:{key}";
  24. }
  25. }
  26. }
  27.  
  28. using System;
  29. using System.Runtime.Caching;
  30. using System.Threading.Tasks;
  31.  
  32. namespace Cacher
  33. {
  34. public class Cacher<T>
  35. {
  36. public delegate T CacheEntryGet(string key);
  37. private MemoryCache Cache { get; set; } = new MemoryCache("long");
  38.  
  39. private CacheItemPolicy ImmediatePolicy => new CacheItemPolicy
  40. {
  41. AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(3)),
  42. Priority = CacheItemPriority.Default,
  43. RemovedCallback = DidRemove
  44. };
  45.  
  46. private CacheItemPolicy RegularPolicy => new CacheItemPolicy
  47. {
  48. AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(20)),
  49. Priority = CacheItemPriority.Default,
  50. RemovedCallback = DidRemove
  51. };
  52.  
  53. private CacheItemPolicy NoRemovePolicy => new CacheItemPolicy
  54. {
  55. Priority = CacheItemPriority.NotRemovable
  56. };
  57.  
  58. private async Task GetFreshContent(CacheEntryRemovedArguments args)
  59. {
  60. await Task.Run(() =>
  61. {
  62. Cache.Set(args.CacheItem, NoRemovePolicy);
  63.  
  64. var item = args.CacheItem.Value as Cacheable<T>;
  65.  
  66. item.Obj = item.Getter(args.CacheItem.Key);
  67.  
  68. var policy = RegularPolicy;
  69.  
  70. Cache.Set(args.CacheItem, policy);
  71. });
  72. }
  73.  
  74. private void DidRemove(CacheEntryRemovedArguments args)
  75. {
  76. GetFreshContent(args);
  77. }
  78.  
  79. public void Add(string key, CacheEntryGet getter)
  80. {
  81. var item = new Cacheable<T>
  82. {
  83. Getter = getter
  84. };
  85.  
  86. Cache.Set(key, item, ImmediatePolicy);
  87. }
  88.  
  89. public T Get(string key) => (Cache[key] as Cacheable<T>).Obj;
  90. }
  91. }
Add Comment
Please, Sign In to add comment