Skip to content

Instantly share code, notes, and snippets.

@thecodeite
Last active December 26, 2015 12:59
Show Gist options
  • Save thecodeite/7154928 to your computer and use it in GitHub Desktop.
Save thecodeite/7154928 to your computer and use it in GitHub Desktop.
LazyCache
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