2013-05-01 01:11:00 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Concurrent;
|
2013-05-23 05:12:01 +00:00
|
|
|
|
using System.Collections.Generic;
|
2013-05-01 01:11:00 +00:00
|
|
|
|
using NzbDrone.Common.EnsureThat;
|
|
|
|
|
|
|
|
|
|
namespace NzbDrone.Common.Cache
|
|
|
|
|
{
|
|
|
|
|
public class Cached<T> : ICached<T>
|
|
|
|
|
{
|
|
|
|
|
private readonly ConcurrentDictionary<string, T> _store;
|
|
|
|
|
|
|
|
|
|
public Cached()
|
|
|
|
|
{
|
|
|
|
|
_store = new ConcurrentDictionary<string, T>();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void Set(string key, T value)
|
|
|
|
|
{
|
|
|
|
|
Ensure.That(() => key).IsNotNullOrWhiteSpace();
|
2013-05-23 05:12:01 +00:00
|
|
|
|
_store[key] = value;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public T Get(string key)
|
|
|
|
|
{
|
|
|
|
|
return Get(key, () => { throw new KeyNotFoundException(key); });
|
2013-05-01 01:11:00 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public T Get(string key, Func<T> function)
|
|
|
|
|
{
|
|
|
|
|
Ensure.That(() => key).IsNotNullOrWhiteSpace();
|
|
|
|
|
|
|
|
|
|
T value;
|
|
|
|
|
|
|
|
|
|
if (!_store.TryGetValue(key, out value))
|
|
|
|
|
{
|
|
|
|
|
value = function();
|
|
|
|
|
Set(key, value);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return value;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public bool ContainsKey(string key)
|
|
|
|
|
{
|
|
|
|
|
Ensure.That(() => key).IsNotNullOrWhiteSpace();
|
|
|
|
|
return _store.ContainsKey(key);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void Clear()
|
|
|
|
|
{
|
|
|
|
|
_store.Clear();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void Remove(string key)
|
|
|
|
|
{
|
|
|
|
|
Ensure.That(() => key).IsNotNullOrWhiteSpace();
|
|
|
|
|
T value;
|
|
|
|
|
_store.TryRemove(key, out value);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|