gpt4 book ai didi

c# - 为什么 MemoryCache 中的滑动过期行为如此奇怪?

转载 作者:行者123 更新时间:2023-11-30 20:49:53 26 4
gpt4 key购买 nike

我不明白在 .NET 4.0 的 System.Runtime.Caching.MemoryCache 中滑动过期应该如何工作。

根据文档,过期时间跨度是“在从缓存中逐出缓存条目之前必须访问缓存条目的时间跨度。”

但是下面的单元测试失败了:

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)
{
}

最佳答案

延长超时时间似乎可以解决问题。让它在我的机器上运行 2 秒:

private readonly TimeSpan timeout = TimeSpan.FromSeconds(2);

我猜现在的缓存机制在时间上不是很准确,但实际上你不会保留半秒的缓存。

关于c# - 为什么 MemoryCache 中的滑动过期行为如此奇怪?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22960525/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com