WebDavCacheBase.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. using System;
  2. using System.Runtime.Caching;
  3. namespace WebDAVSharp.Server.Utilities
  4. {
  5. /// <summary>
  6. /// </summary>
  7. internal class WebDavCacheBase
  8. {
  9. private readonly MemoryCache _cache;
  10. private readonly object _padlock = new object();
  11. private readonly CacheItemPolicy _policy;
  12. private readonly string name;
  13. /// <summary>
  14. /// </summary>
  15. public WebDavCacheBase()
  16. {
  17. _policy = new CacheItemPolicy
  18. {
  19. Priority = CacheItemPriority.Default,
  20. AbsoluteExpiration = DateTimeOffset.Now.AddHours(1.00),
  21. RemovedCallback = RemovedCallback
  22. };
  23. name = GetType().Name + "_Cache";
  24. _cache = new MemoryCache(name);
  25. }
  26. /// <summary>
  27. /// </summary>
  28. /// <param name="policy"></param>
  29. protected WebDavCacheBase(CacheItemPolicy policy)
  30. {
  31. _policy = policy;
  32. name = GetType().Name + "_Cache";
  33. _cache = new MemoryCache(name);
  34. }
  35. /// <summary>
  36. /// </summary>
  37. public MemoryCache Cache => _cache;
  38. private void RemovedCallback(CacheEntryRemovedArguments arguments)
  39. {
  40. }
  41. /// <summary>
  42. /// </summary>
  43. /// <param name="key"></param>
  44. /// <param name="remove"></param>
  45. /// <returns></returns>
  46. public virtual object GetCachedObject(string key, bool remove = false)
  47. {
  48. lock (_padlock)
  49. {
  50. object res = _cache[key];
  51. if (res != null && remove)
  52. _cache.Remove(key);
  53. return res;
  54. }
  55. }
  56. /// <summary>
  57. /// </summary>
  58. /// <param name="key"></param>
  59. /// <param name="value"></param>
  60. public virtual void AddCacheObject(string key, object value)
  61. {
  62. lock (_padlock)
  63. {
  64. _cache.Set(key, value, _policy);
  65. }
  66. }
  67. /// <summary>
  68. /// </summary>
  69. /// <param name="key"></param>
  70. /// <param name="value"></param>
  71. /// <param name="timeToExpire"></param>
  72. public virtual void AddCacheObject(string key, object value, TimeSpan timeToExpire)
  73. {
  74. lock (_padlock)
  75. {
  76. CacheItemPolicy itempolicy = new CacheItemPolicy
  77. {
  78. Priority = CacheItemPriority.Default,
  79. AbsoluteExpiration = DateTimeOffset.Now.Add(timeToExpire),
  80. RemovedCallback = RemovedCallback
  81. };
  82. _cache.Set(key, value, _policy);
  83. }
  84. }
  85. /// <summary>
  86. /// </summary>
  87. /// <param name="key"></param>
  88. public virtual void RemoveCacheObject(string key)
  89. {
  90. lock (_padlock)
  91. {
  92. _cache.Remove(key);
  93. }
  94. }
  95. }
  96. }