通过.NET MemoryCache中的CacheItemPolicy过期的缓存项 [英] Expiring a cached item via CacheItemPolicy in .NET MemoryCache

查看:553
本文介绍了通过.NET MemoryCache中的CacheItemPolicy过期的缓存项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对CacheItemPolicy上的AbsoluteExpiration属性感到困惑。

I'm confused about the AbsoluteExpiration property on CacheItemPolicy.

有关该MSDN文档的信息说:驱逐缓存项之前必须经过的时间。它使用System.DateTimeOffset定义时间段。

The MSDN documentation for it says "The period of time that must pass before a cache entry is evicted." It uses a System.DateTimeOffset to define the "period of time".

但是,如果您查看 DateTimeOffset的MSDN文档,它表示代表了一个时间点...相对于协调世界时(UTC)。另请参考 StackOverflow线程

But if you look at DateTimeOffset's MSDN documentation, it says that it "represents a point in time ... relative to Coordinated Universal Time (UTC)." Reference also this StackOverflow thread.

您看到问题了吗? AbsoluteExpiration期望有一个时间段(例如5秒或2个小时),但是它需要一个代表时间点的对象(例如EST 12月21日,06:14:00)。

Do you see the problem? AbsoluteExpiration expects a "period in time" (like 5 seconds or 2 hours), but it requires an object that represents a "point in time" (like Dec 21, 2012, 06:14:00 EST).

在下面的代码中,我为所有项目定义了一个策略。我希望每个项目都在添加后 cacheExpiryInSeconds 秒后过期。

In the code below, I define a single policy for all items. I want every item to expire cacheExpiryInSeconds seconds after they are added. Can someone verify that I'm doing this the correct way?

public class MyCache : IRoutingInfoCache
{
    MemoryCache _routingInfoCache;
    CacheItemPolicy _cachePolicy;


    public MyCache(int cacheExpiryInSeconds)
    {
        _routingInfoCache = new MemoryCache("myCache");
        _cachePolicy = new CacheItemPolicy() {
            AbsoluteExpiration = 
                new DateTimeOffset(
                    DateTime.UtcNow.AddSeconds(cacheExpiryInSeconds))
        };
    }


    public void Put(string key, object cacheItem)
    {
        // based on how I constructed _cachePolicy, will this item expire
        // in cacheExpiryInSeconds seconds?
        _routingInfoCache.Add(new CacheItem(key, cacheItem), _cachePolicy);
    }
}


推荐答案

缓存遵守UTC时间以提供统一的时间计算,因此您可以使用UTC指定一个缓存条目应过期的时间点,然后缓存将从现在开始计算适当的差异并按预期过期。

Caching adheres to UTC time to offer uniform time calculations, so you specify a point in time at which the cached entry should expire, in UTC, and the cache will calculate the appropriate difference from now and expire it as expected.

您的代码将无法按预期运行,因为一旦 cacheExpiryInSeconds ,您的绝对过期将之前输入秒过去,导致立即驱逐。我知道,在不久的将来设置AbsoluteExpiration时,您无法共享CacheItemPolicy实例。 :)

Your code will not work as expected since your absolute expiration will be before your cache item is entered once cacheExpiryInSeconds seconds pass, resulting in immediate eviction. You cannot share a CacheItemPolicy instance when AbsoluteExpiration is set in the near future, annoying I know. :)

这篇关于通过.NET MemoryCache中的CacheItemPolicy过期的缓存项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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