Dai*_*ges 2 c# caching dictionary unit-testing
我想创建一个返回值的类。此值将在字典对象中缓存2分钟。在这2分钟内,我需要返回缓存的值,在那几分钟之后,字典缓存对象应再次读取该值。我需要使用Dictionary对象而不是memorychache之类的东西,并且应该在Test方法类中执行代码,而不是Windows窗体或wpf。
我不知道在测试方法中2分钟后如何使字典对象过期。
public class CacheClass
{
public string GetValue()
{
Dictionary<int, string> Cache = new Dictionary<int, string>();
string value1 = "Lina";
string value2 = "Jack";
return "cached value";
}
}
Run Code Online (Sandbox Code Playgroud)
public class Cache<TKey, TValue>
{
private readonly Dictionary<TKey, CacheItem<TValue>> _cache = new Dictionary<TKey, CacheItem<TValue>>();
public void Store(TKey key, TValue value, TimeSpan expiresAfter)
{
_cache[key] = new CacheItem<TValue>(value, expiresAfter);
}
public TValue Get(TKey key)
{
if (!_cache.ContainsKey(key)) return default(TValue);
var cached = _cache[key];
if (DateTimeOffset.Now - cached.Created >= cached.ExpiresAfter)
{
_cache.Remove(key);
return default(TValue);
}
return cached.Value;
}
}
public class CacheItem<T>
{
public CacheItem(T value, TimeSpan expiresAfter)
{
Value = value;
ExpiresAfter = expiresAfter;
}
public T Value { get; }
internal DateTimeOffset Created { get; } = DateTimeOffset.Now;
internal TimeSpan ExpiresAfter { get; }
}
var cache = new Cache<int, string>();
cache.Store(1, "SomeString", TimeSpan.FromMinutes(2));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3623 次 |
| 最近记录: |