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

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

bool result= MemoryCache.Default.Add(cacheKey, dataToCache, cacheItemPolicy) 

结果的值为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); } 

您没有正确设置AbsoluteExpiration属性。

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

您将DateTime.Now作为DateTime参数传递,因此您实际要做的是将缓存项设置为立即过期。

如果您希望缓存的项目存活一个小时,则设置到期时间如下:

 cacheItemPolicy.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddHours(1)); 

您是否有可能将策略的AbsoluteExpiration设置为零或非常小的DateTimeOffset