Created
October 6, 2014 20:14
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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