项目到期后无法将项目添加到内存缓存

时间:2015-08-06 12:16:55

标签: c# .net caching

我正在使用内存缓存来阻止重新处理从队列中收到的邮件。

以下是我创建缓存和添加项目的方法:

        _cache = new MemoryCache("TransactionProcessorCache");

        _policy = new CacheItemPolicy
        {
            UpdateCallback = null,
            AbsoluteExpiration = DateTimeOffset.UtcNow.AddMinutes(1)
        };

        _cache.Add("unique key", "value", _policy);

我将第一项添加到缓存中,我可以检索此项目1分钟,这是预期的。

但是,一旦第一个项目到期并且缓存变空,就无法检索我添加到缓存中的后续项目。尽管从_cache.Add(...)调用中获得返回值“true”,缓存仍然表现得像空一样。

我正在使用.NET Framework 4.5.1。该应用程序是一个控制台应用程这里的MemoryCache来自System.Runtime.Caching

2 个答案:

答案 0 :(得分:2)

再看看这一行

AbsoluteExpiration = DateTimeOffset.UtcNow.AddMinutes(1)

您从当前时间永久 1分钟后禁用缓存。一分钟过期后,您将不得不重新创建策略(或者每次要添加项目时创建策略,然后它会按照您期望的方式运行)。

请参阅@ JD.B答案,了解更好的常量政策。

答案 1 :(得分:1)

@ Sinatr的回答清除了它; AbsoluteExpiration政策使政策本身失效。这意味着您需要为添加的每个项目创建新策略;正如@Sinatr在他的回答中所说的那样。

同时,SlidingExpiration策略跟踪上次访问项目的时间,如果在指定时间内未访问该项目,则仅删除该项目。因此允许您重复使用相同的策略,但它的行为略有不同,因为项目的到期计时器每次访问时都会重置。

SlidingExpiration示例:

MemoryCache cache = new MemoryCache("C");
CacheItemPolicy policy = new CacheItemPolicy
{
    UpdateCallback = null,
    SlidingExpiration = new TimeSpan(0, 0, 5)
};

cache.Add("key", "value", policy);
Console.WriteLine("1) " + cache.Get("key")); // Prints `1) value`

System.Threading.Thread.Sleep(5250); // Wait for "key" to expire
Console.WriteLine("2) " + cache.Get("key")); // Prints `2) `

// Just showing the the cache policy still works once an item expires.
cache.Add("key2", "value2", policy);
Console.WriteLine("3) " + cache.Get("key2")); // Prints `3) value2`

System.Threading.Thread.Sleep(5250); // Wait for "key2" to expire
Console.WriteLine("4) " + cache.Get("key2")); // Prints `4) `