Skip to content

Instantly share code, notes, and snippets.

@RhysC
Last active August 29, 2015 14:05
Show Gist options
  • Save RhysC/062a46f5f77235c2425e to your computer and use it in GitHub Desktop.
Save RhysC/062a46f5f77235c2425e to your computer and use it in GitHub Desktop.
Cache of T
using System;
namespace MyNameSpace
{
public class Cacheable<T> where T : class
{
private readonly Func<T> _refresh;
private T _current;
private DateTime _timestamp;
private readonly TimeSpan _limit;
public Cacheable(Func<T> refresh, TimeSpan limit)
{
_refresh = refresh;
_limit = limit;
}
public Cacheable(Func<T> refresh)
: this(refresh, TimeSpan.FromMinutes(60))
{ }
public T Get()
{
if (_current == null || HasExpired())
{
return RefreshCache();
}
return _current;
}
private T RefreshCache()
{
_current = _refresh();
_timestamp = DateTime.UtcNow;
return _current;
}
private bool HasExpired()
{
var timeElapsed = DateTime.UtcNow - _timestamp;
return timeElapsed > _limit;
}
}
}
using System;
using System.Threading;
using Xunit;
namespace MyNameSpace.Tests
{
public class CacheTests
{
[Fact]
public void CanReuseCachedObject()
{
var cache = new Cacheable<string>(() => DateTime.Now.ToString(), TimeSpan.FromSeconds(10));
var ob1 = cache.Get();
Thread.Sleep(1000);
var ob2 = cache.Get();
Assert.Equal(ob1, ob2);
}
[Fact]
public void CanGetNewObjectOnceExpired()
{
var cache = new Cacheable<string>(() => DateTime.Now.ToString(), TimeSpan.FromTicks(1));
var ob1 = cache.Get();
Thread.Sleep(1000);
var ob2 = cache.Get();
Assert.NotEqual(ob1, ob2);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment