Skip to content

Instantly share code, notes, and snippets.

@benbrandt22
Created October 6, 2014 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benbrandt22/df4aa493b732d1dcc44b to your computer and use it in GitHub Desktop.
Save benbrandt22/df4aa493b732d1dcc44b to your computer and use it in GitHub Desktop.
TimedCacheValue - Simple C# class which acts like Lazy<T> but only keeps the value for a specified amount of time.
using System;
using System.Runtime.Caching;
namespace SampleApp.Support
{
public class TimeCachedValue<T>
{
private readonly Func<T> valueFactory;
private readonly TimeSpan objectLifeSpan;
MemoryCache cache = MemoryCache.Default;
private string cacheIdentifierKey = Guid.NewGuid().ToString();
public TimeCachedValue(Func<T> valueFactory, TimeSpan expireTime)
{
this.valueFactory = valueFactory;
this.objectLifeSpan = expireTime;
}
public T Value {
get {
if (this.cache.Get(this.cacheIdentifierKey) == null)
{
// get a new value from the supplied factory function, and store it in the cache
T value = this.valueFactory.Invoke();
// set up a cache policy...
var cacheItemPolicy = new CacheItemPolicy() { AbsoluteExpiration = DateTimeOffset.Now.Add(this.objectLifeSpan) };
// put it in the cache
this.cache.Set(this.cacheIdentifierKey, value, cacheItemPolicy);
}
// return the value from the in-memory cache
T returnValue = (T)this.cache.Get(this.cacheIdentifierKey);
return returnValue;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment