2011-05-19 71 views
14

我尝试添加使用下面的方法添加项目到MemoryCache.Default实例:MemoryCache.Add返回true,但不会增加项目缓存

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); 
    } 
+0

是'cacheItemPolicy'使用哪些设置? – LukeH 2011-05-19 14:09:33

+0

+ 3600秒&absoluteExpiration = true。 – Jason 2011-05-19 14:49:17

回答

24

您没有正确设置AbsoluteExpiration属性。

,你传递给DateTimeOffset constructorTimeSpan参数应该是从传递DateTime值的UTC偏移,要添加到您的生成抵消一些任意的时间跨度。你的传球时间是3600秒 - 也就是一个小时 - 这纯粹是巧合,因为大概你是在英国的BST目前比UTC快一个小时的。

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

如果你希望你的缓存项住了一个小时,然后这样设置过期时间:

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

现货,谢谢卢克。 – Jason 2011-05-19 16:22:58

+7

我会建议使用DateTimeOffset.UtcNow.AddHours(1)。由于需要计算本地时间,因此DateTime.Now很慢,并且无论如何,MemoryCache都会忽略本地时间。 – 2012-04-09 10:45:18

0

是否有可能要设置策略的AbsoluteExpiration为零或很小,DateTimeOffset

+0

它设置为+3600秒,所以不应该是这样。 – Jason 2011-05-19 14:48:56

+0

cacheKey是什么类型? – 2011-05-19 15:04:26

+0

cacheKey是一个字符串。 – Jason 2011-05-19 15:07:51

相关问题