结合滑动和绝对呼气

And*_*res 19 .net c# caching

我想使用System.Runtime.Caching.MemoryCache来缓存我的一些对象.我想确保该对象每天刷新一次(绝对到期),但如果在最后一小时内没有使用(滑动到期),我也想让它过期.我尝试做:

object item = "someitem";
var cache = MemoryCache.Default;
var policy = new CacheItemPolicy();
policy.AbsoluteExpiration = DateTime.Now.AddDays(1);
policy.SlidingExpiration = TimeSpan.FromHours(1);
cache.Add("somekey", item, policy);
Run Code Online (Sandbox Code Playgroud)

但我得到一个"ArgumentException","AbsoluteExpiration必须是DateTimeOffset.MaxValue或SlidingExpiration必须是TimeSpan.Zero".

小智 10

您可以使用CacheEntryChangeMonitor实现两个方案缓存过期.插入没有绝对过期信息的缓存项,然后使用此项创建一个空的monitorChange并将其与第二个缓存项链接,您将在其中实际保存slidingTimeOut信息.

        object data = new object();
        string key = "UniqueIDOfDataObject";
        //Insert empty cache item with absolute timeout
        string[] absKey = { "Absolute" + key };
        MemoryCache.Default.Add("Absolute" + key, new object(), DateTimeOffset.Now.AddMinutes(10));

        //Create a CacheEntryChangeMonitor link to absolute timeout cache item
        CacheEntryChangeMonitor monitor = MemoryCache.Default.CreateCacheEntryChangeMonitor(absKey);

        //Insert data cache item with sliding timeout using changeMonitors
        CacheItemPolicy itemPolicy = new CacheItemPolicy();
        itemPolicy.ChangeMonitors.Add(monitor);
        itemPolicy.SlidingExpiration = new TimeSpan(0, 60, 0);
        MemoryCache.Default.Add(key, data, itemPolicy, null);
Run Code Online (Sandbox Code Playgroud)


Cyb*_*axs 5

使用 ILSpy 进行快速反思,在调用时显示此代码MemoryCache.Add

if (policy.AbsoluteExpiration != ObjectCache.InfiniteAbsoluteExpiration && policy.SlidingExpiration != ObjectCache.NoSlidingExpiration)
    {
        throw new ArgumentException(R.Invalid_expiration_combination, "policy");
    }
Run Code Online (Sandbox Code Playgroud)

因此,本机不支持绝对过期和滑动过期的这种组合。

您应该转向自定义实现。