【发布时间】:2014-04-09 11:01:37
【问题描述】:
我不明白在 System.Runtime.Caching.MemoryCache 和 .NET 4.0 中应该如何滑动到期。
根据文档,过期时间跨度是“在将缓存条目从缓存中逐出之前必须访问缓存条目的时间跨度。”
但是下面的单元测试失败了:
private const string AnyKey = "key";
private const string AnyValue = "value";
private readonly TimeSpan timeout = TimeSpan.FromSeconds(0.5);
private void WaitSixtyPercentOfTheTimeout()
{
Thread.Sleep(TimeSpan.FromSeconds(timeout.TotalSeconds*0.6));
}
[Test]
public void Get_RefreshesTimeoutOfSlidingExpiration()
{
var cache = MemoryCache.Default;
cache.Set(AnyKey, AnyValue, new CacheItemPolicy {SlidingExpiration = timeout});
WaitSixtyPercentOfTheTimeout();
cache[AnyKey].Should().Be(AnyValue);
WaitSixtyPercentOfTheTimeout();
cache[AnyKey].Should().Be(AnyValue);
}
private void UpdateCallback(CacheEntryUpdateArguments arguments)
{
}
巧合的是,我做了一个小改动来解决这个问题。但是,如果它是错误或功能,现在有人吗?
一旦设置了 UpdateCallBack,过期就会按预期工作:
// [...]
[Test]
public void Get_RefreshesTimeoutOfSlidingExpiration()
{
var cache = MemoryCache.Default;
cache.Set(AnyKey, AnyValue, new CacheItemPolicy {SlidingExpiration = timeout, UpdateCallback = UpdateCallback});
WaitSixtyPercentOfTheTimeout();
cache[AnyKey].Should().Be(AnyValue);
WaitSixtyPercentOfTheTimeout();
cache[AnyKey].Should().Be(AnyValue);
}
private void UpdateCallback(CacheEntryUpdateArguments arguments)
{
}
【问题讨论】:
标签: c# .net caching memorycache