Last active
December 26, 2015 12:59
-
-
Save thecodeite/7154928 to your computer and use it in GitHub Desktop.
LazyCache
This file contains hidden or 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 Euromoney.Isis.Api.Services | |
{ | |
public abstract class LazyCache | |
{ | |
protected static readonly object ValueLock = new object(); | |
} | |
public sealed class LazyCache<T> : LazyCache | |
{ | |
private readonly string _key; | |
private readonly Func<T> _valueFactory; | |
private readonly TimeSpan _cacheLength; | |
private readonly ObjectCache _cache = MemoryCache.Default; | |
public LazyCache(string key, Func<T> valueFactory, TimeSpan cacheLength) | |
{ | |
_key = "LazyCache"+key; | |
_valueFactory = valueFactory; | |
_cacheLength = cacheLength; | |
} | |
public T Value | |
{ | |
get | |
{ | |
if (IsCached()) | |
{ | |
return (T)_cache[_key]; | |
} | |
lock (ValueLock) | |
{ | |
if (!IsCached()) | |
{ | |
var value = _valueFactory.Invoke(); | |
_cache.Add(_key, value, DateTimeOffset.UtcNow.Add(_cacheLength)); | |
} | |
} | |
return (T)_cache[_key]; | |
} | |
} | |
private bool IsCached() | |
{ | |
return _cache.Contains(_key); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment