CacheExpires.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // This file implements the classes ExpiresEntryRef and CacheExpires missing from .NET reference source
  2. using System.Threading;
  3. namespace System.Runtime.Caching
  4. {
  5. class ExpiresEntryRef
  6. {
  7. public static ExpiresEntryRef INVALID = new ExpiresEntryRef ();
  8. public bool IsInvalid {
  9. get { return this == INVALID; }
  10. }
  11. }
  12. class CacheExpiresHelper : ICacheEntryHelper
  13. {
  14. public int Compare(MemoryCacheEntry entry1, MemoryCacheEntry entry2)
  15. {
  16. return DateTime.Compare (entry1.UtcAbsExp , entry2.UtcAbsExp);
  17. }
  18. public DateTime GetDateTime (MemoryCacheEntry entry)
  19. {
  20. return entry.UtcAbsExp;
  21. }
  22. }
  23. class CacheExpires : CacheEntryCollection
  24. {
  25. public static TimeSpan MIN_UPDATE_DELTA = new TimeSpan (0, 0, 1);
  26. public static TimeSpan EXPIRATIONS_INTERVAL = new TimeSpan (0, 0, 20);
  27. public static CacheExpiresHelper helper = new CacheExpiresHelper ();
  28. Timer timer;
  29. public CacheExpires (MemoryCacheStore store)
  30. : base (store, helper)
  31. {
  32. }
  33. public new void Add (MemoryCacheEntry entry)
  34. {
  35. entry.ExpiresEntryRef = new ExpiresEntryRef ();
  36. base.Add (entry);
  37. }
  38. public new void Remove (MemoryCacheEntry entry)
  39. {
  40. base.Remove (entry);
  41. entry.ExpiresEntryRef = ExpiresEntryRef.INVALID;
  42. }
  43. public void UtcUpdate (MemoryCacheEntry entry, DateTime utcAbsExp)
  44. {
  45. base.Remove (entry);
  46. entry.UtcAbsExp = utcAbsExp;
  47. base.Add (entry);
  48. }
  49. public void EnableExpirationTimer (bool enable)
  50. {
  51. if (enable) {
  52. if (timer != null)
  53. return;
  54. var period = (int) EXPIRATIONS_INTERVAL.TotalMilliseconds;
  55. timer = new Timer ((o) => FlushExpiredItems (true), null, period, period);
  56. } else {
  57. timer.Dispose ();
  58. timer = null;
  59. }
  60. }
  61. public int FlushExpiredItems (bool blockInsert)
  62. {
  63. return base.FlushItems (DateTime.UtcNow, CacheEntryRemovedReason.Expired, blockInsert);
  64. }
  65. }
  66. }