Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么MemoryCache中的滑动过期行为如此奇怪?_C#_.net_Caching_Memorycache - Fatal编程技术网

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

C# 为什么MemoryCache中的滑动过期行为如此奇怪?,c#,.net,caching,memorycache,C#,.net,Caching,Memorycache,我不明白滑动过期应该如何在System.Runtime.Caching.MemoryCache和.NET 4.0中工作 根据文档,过期时间跨度是“从缓存中取出缓存项之前必须访问缓存项的时间跨度。” 但是,以下单元测试失败: private const string AnyKey = "key"; private const string AnyValue = "value"; private readonly TimeSpan timeout = TimeSpan.FromSeconds(0.

我不明白滑动过期应该如何在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)
{
}
巧合的是,我做了一个小改动,解决了这个问题。然而,现在有人知道这是一个bug还是一个特性吗

一旦设置了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);

我猜当前的缓存机制在计时方面不是很准确,但实际上,无论如何,您都不会保持缓存半秒钟。

这很奇怪,但似乎是正确的解决方案。在我开始在测试中使用超过1秒的过期时间之前,我认为SlidingExpiration设置对我不起作用。为了保持此答案的帮助性,请检查System.Runtime.Caching中的一些代码,确定最短1秒。