MemoryCache.Add返回true但不向缓存添加项

Jas*_*son 16 .net c#

我正在尝试使用Add方法将项添加到MemoryCache.Default实例,如下所示:

bool result= MemoryCache.Default.Add(cacheKey, dataToCache, cacheItemPolicy)
Run Code Online (Sandbox Code Playgroud)

结果的值为true,表示当我尝试在缓存为空后立即检索它时,该项已添加到缓存中.我还尝试使用Set方法添加项目,其结果与空缓存相同.

缓存具有默认的99Mb内存限制,因此不会显示没有空间来添加新项目.

有任何想法吗?


private static void InsertCachedData(string cacheKey, object dataToCache, string[] dependantCacheKeys)
    {
        CacheItemPolicy cacheItemPolicy = new CacheItemPolicy();

        cacheItemPolicy.AbsoluteExpiration = new DateTimeOffset(DateTime.Now, new TimeSpan(hours: 0, minutes: 0, seconds: 3600));

        if (dependantCacheKeys != null && dependantCacheKeys.Length > 0)
        {
            cacheItemPolicy.ChangeMonitors.Add(MemoryCache.Default.CreateCacheEntryChangeMonitor(dependantCacheKeys));
        }

        MemoryCache.Default.Add(cacheKey, dataToCache, cacheItemPolicy);

        logger.DebugFormat("Cache miss for VehiclesProvider call with key {0}", cacheKey);
    }
Run Code Online (Sandbox Code Playgroud)

Luk*_*keH 26

您没有AbsoluteExpiration正确设置属性.

TimeSpan传递给DateTimeOffset构造函数的参数应该是传递DateTime值与UTC的偏移量,而不是要添加的任意时间跨度以生成偏移量.你通过了3600秒 - 即一小时 - 这纯粹是巧合,因为据推测,你所在的英国BST目前比UTC早一个小时.

你DateTime.Now作为DateTime参数传递,所以你实际上正在做的是将缓存项设置为立即过期.

如果您希望缓存项目存在一小时,则设置过期时间如下:

cacheItemPolicy.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddHours(1));
Run Code Online (Sandbox Code Playgroud)

  • 我建议使用DateTimeOffset.UtcNow.AddHours(1).由于需要计算本地时间,DateTime.Now很慢,而MemoryCache无论如何都忽略了本地时间. (7认同)