using System;
namespace NadekoBot.Core.Common.Caching
{
///
/// A caching object which loads its value with a factory method when it expires.
///
/// Type of the value which is cached.
public class FactoryCache : IFactoryCache
{
public DateTime LastUpdate { get; set; } = DateTime.MinValue;
private readonly object _locker = new object();
private TimeSpan _expireAfter;
private readonly Func _factory;
private T Value;
///
/// Creates a new factory cache object.
///
/// Method which loads the value when it expires or if it's not loaded the first time.
/// Time after which the value will be reloaded.
/// Should the value be loaded right away. If set to false, value will load when it's first retrieved.
public FactoryCache(Func factory, TimeSpan expireAfter,
bool loadImmediately = false)
{
_expireAfter = expireAfter;
_factory = factory;
if (loadImmediately)
{
Value = _factory();
LastUpdate = DateTime.UtcNow;
}
}
public T GetValue()
{
lock (_locker)
{
if (DateTime.UtcNow - LastUpdate > _expireAfter)
{
LastUpdate = DateTime.UtcNow;
return Value = _factory();
}
return Value;
}
}
}
}