title: Expiring Lazy<T> class
body: <p>Is there any class in .NET library which can act as expiring <code>Lazy&lt;T&gt;</code>? </p>
  
  <p>The idea is that <code>Func&lt;T&gt;</code> value factory lambda is passed there and invoked only first time or if timeout is passed.</p>
  
  <p>I've created simple class to do that, but I'd like to avoid inventing a wheel.</p>
  
  <pre><code>public class ExpiringLazy&lt;T&gt;
  {
      private readonly object valueGetLock = new object();
      private readonly Func&lt;T&gt; valueFactory;
      private readonly TimeSpan timeout;
  
      private T cachedValue;
      private DateTime cachedTime;
  
      public T Value
      {
          get
          {
              Thread.MemoryBarrier();
  
              if (cachedTime.Equals(default(DateTime)) || DateTime.UtcNow &gt; cachedTime + timeout)
              {
                  lock (valueGetLock)
                  {
                      if (cachedTime.Equals(default(DateTime)) || DateTime.UtcNow &gt; cachedTime + timeout)
                      {
                          cachedValue = valueFactory();
                          Thread.MemoryBarrier();
                          cachedTime = DateTime.UtcNow;
                      }
                  }
              }
  
              return cachedValue;
          }
      } 
  
      public ExpiringLazy(Func&lt;T&gt; valueFactory, TimeSpan timeout)
      {
          if (valueFactory == null) throw new ArgumentNullException(nameof(valueFactory));
          this.valueFactory = valueFactory;
          this.timeout = timeout;
      }
  }
  </code></pre>