Advertisement
Guest User

CachedField

a guest
Jan 28th, 2020
438
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.07 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6.  
  7. namespace CachedField
  8. {
  9.     public class CachedField<T>
  10.     {
  11.         public static readonly TimeSpan DefaultUpdateSpan = new TimeSpan(0, 5, 0);
  12.  
  13.         private T value;
  14.         private Func<T> getValueDelegate;
  15.         private ReaderWriterLockSlim rwLock;
  16.         private DateTime lastUpdate;
  17.  
  18.         private readonly TimeSpan updateSpan;
  19.  
  20.  
  21.         private bool InvalidateRequired()
  22.         {
  23.             bool result = false;
  24.             rwLock.EnterReadLock();
  25.             if (DateTime.Now.Subtract(lastUpdate) > updateSpan)
  26.             {
  27.                 result = true;
  28.             }
  29.             rwLock.ExitReadLock();
  30.             return result;
  31.         }
  32.  
  33.         public CachedField(Func<T> getValueDelegate) : this(getValueDelegate, DefaultUpdateSpan)
  34.         {
  35.  
  36.         }
  37.  
  38.         public CachedField(Func<T> getValueDelegate, TimeSpan updateSpan)
  39.         {
  40.             if (getValueDelegate == null)
  41.                 throw new ArgumentNullException("getValueDelegate");
  42.  
  43.             this.rwLock = new ReaderWriterLockSlim();
  44.  
  45.             this.updateSpan = updateSpan;
  46.             this.getValueDelegate = getValueDelegate;
  47.  
  48.             this.Invalidate();
  49.         }
  50.  
  51.         public T Value
  52.         {
  53.             get
  54.             {
  55.                 if (InvalidateRequired())
  56.                 {
  57.                     Invalidate();
  58.                 }
  59.  
  60.                 //Enter read lock to prevent value writing
  61.                 rwLock.EnterReadLock();
  62.                 T temp = value;
  63.                 rwLock.ExitReadLock();
  64.  
  65.                 return temp;
  66.             }
  67.         }
  68.        
  69.         public void Invalidate()
  70.         {
  71.             if (!rwLock.TryEnterWriteLock(1))
  72.             {
  73.                 //If it's already updating cache, don't update again.
  74.                 return;
  75.             }
  76.  
  77.             value = getValueDelegate();
  78.             lastUpdate = DateTime.Now;
  79.             rwLock.ExitWriteLock();
  80.         }
  81.     }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement