sonarr-repo-only/NzbDrone.Common/Cache/Cached.cs

99 lines
2.3 KiB
C#
Raw Normal View History

2013-05-01 01:11:00 +00:00
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
2013-07-24 00:35:35 +00:00
using System.Linq;
2013-05-01 01:11:00 +00:00
using NzbDrone.Common.EnsureThat;
namespace NzbDrone.Common.Cache
{
2013-07-24 00:35:35 +00:00
2013-05-01 01:11:00 +00:00
public class Cached<T> : ICached<T>
{
2013-07-24 00:35:35 +00:00
private class CacheItem
2013-05-01 01:11:00 +00:00
{
2013-07-24 00:35:35 +00:00
public T Object { get; private set; }
public DateTime? ExpiryTime { get; private set; }
public CacheItem(T obj, TimeSpan? lifetime = null)
{
Object = obj;
if (lifetime.HasValue)
{
ExpiryTime = DateTime.UtcNow + lifetime.Value;
}
}
public bool IsExpired()
{
return ExpiryTime.HasValue && ExpiryTime.Value < DateTime.UtcNow;
}
2013-05-01 01:11:00 +00:00
}
2013-07-24 00:35:35 +00:00
private readonly ConcurrentDictionary<string, CacheItem> _store;
public Cached()
2013-05-01 01:11:00 +00:00
{
2013-07-24 00:35:35 +00:00
_store = new ConcurrentDictionary<string, CacheItem>();
}
2013-07-24 00:35:35 +00:00
public void Set(string key, T value, TimeSpan? lifetime = null)
{
2013-07-24 00:35:35 +00:00
Ensure.That(() => key).IsNotNullOrWhiteSpace();
_store[key] = new CacheItem(value, lifetime);
2013-05-01 01:11:00 +00:00
}
public T Find(string key)
{
2013-07-24 00:35:35 +00:00
CacheItem value;
_store.TryGetValue(key, out value);
2013-07-24 00:35:35 +00:00
if (value == null)
{
return default(T);
}
if (value.IsExpired())
{
_store.TryRemove(key, out value);
return default(T);
}
return value.Object;
}
2013-07-24 00:35:35 +00:00
public T Get(string key, Func<T> function, TimeSpan? lifeTime = null)
2013-05-01 01:11:00 +00:00
{
Ensure.That(() => key).IsNotNullOrWhiteSpace();
2013-07-24 00:35:35 +00:00
CacheItem cacheItem;
2013-05-01 01:11:00 +00:00
T value;
2013-07-24 00:35:35 +00:00
if (!_store.TryGetValue(key, out cacheItem) || cacheItem.IsExpired())
2013-05-01 01:11:00 +00:00
{
value = function();
2013-07-24 00:35:35 +00:00
Set(key, value, lifeTime);
}
else
{
value = cacheItem.Object;
2013-05-01 01:11:00 +00:00
}
return value;
}
public void Clear()
{
_store.Clear();
}
2013-05-30 23:32:50 +00:00
public ICollection<T> Values
{
get
{
2013-07-24 00:35:35 +00:00
return _store.Values.Select(c => c.Object).ToList();
2013-05-30 23:32:50 +00:00
}
}
2013-07-24 00:35:35 +00:00
2013-05-01 01:11:00 +00:00
}
}