Asp.Net 4.0 CacheItemPolicy滑动到期不正确? [英] Asp.Net 4.0 CacheItemPolicy sliding expiration incorrect?

查看:107
本文介绍了Asp.Net 4.0 CacheItemPolicy滑动到期不正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Runtime.Caching;

using Xunit;

namespace Demo.Caching.Test
{
    class MemoryCacheManagerTest
    {
        [Fact]
        public void Test()
        {
            CacheItemPolicy policy = new CacheItemPolicy();
            policy.SlidingExpiration = TimeSpan.FromSeconds(1);

            MemoryCache.Default.Set("cacheKey4", 4, policy);
            Assert.Equal(4, MemoryCache.Default.Get("cacheKey4"));
            System.Threading.Thread.Sleep(600);
            Assert.Equal(4, MemoryCache.Default.Get("cacheKey4"));
            System.Threading.Thread.Sleep(600);
            Assert.Equal(4, MemoryCache.Default.Get("cacheKey4"));
            // Here I get error
            // Expected: 4, Actual: (null)

            System.Threading.Thread.Sleep(1000);
            Assert.Null(MemoryCache.Default.Get("cacheKey4"));
        }
    }
}


推荐答案

这不是不是,正如其他答案所说的,由于Thread.Sleep()花费的时间比预期的长。

This is not, as the other answers have said, due to Thread.Sleep() taking longer than expected.

MemoryCache 的滑动计时器似乎不太精确。我想这是为了避免锁定,并保持高速缓存的性能。

MemoryCache appears to be pretty imprecise with its sliding timer. I'm guessing that this is so they can avoid locking, and keep up the cache's performance.


  • 如果将滑动到期时间设置为1秒或更短,则缓存项将在1秒后被驱逐,无论它们是多少次

  • 在1到2秒之间,似乎仍然有可能收回缓存项。这可能在某种程度上取决于计算机的负担,并且在很大程度上取决于何时访问这些项目,但并不像您想的那样可预测。例如:

    • 如果我将到期时间设置为1.001秒至1.24秒,并且在两次访问之间睡眠200或250毫秒,它将值保留在缓存中;但是如果我睡了201或249毫秒,该物品就会被逐出。

    • 如果将到期时间设置为1.25秒,则我最多可以睡624毫秒而没有问题,但是如果我达到625毫秒后,缓存项目将被逐出。

    所以我想这课是不要依靠滑动过期来正确工作的小于2秒的值。 PollingInterval 可能与设置为2秒有关。

    So I guess the lesson is to not rely on sliding expirations to work correctly for values under 2 seconds. This may have something to do with the PollingInterval being set to 2 seconds.

    代码:

    var span = TimeSpan.FromSeconds(1); // change as necessary
    var sw = new Stopwatch();
    var cache = new MemoryCache("testcache");
    sw.Start();
    cache.Add("test", "hello", new CacheItemPolicy{SlidingExpiration = span});
    Console.WriteLine(sw.ElapsedMilliseconds);
    for (int i = 0; i < 40; i++)
    {
        Console.WriteLine(sw.ElapsedMilliseconds + ": " + cache.Get("test"));
        Thread.Sleep(50); // change as necessary
    }
    

    这篇关于Asp.Net 4.0 CacheItemPolicy滑动到期不正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆