2011-05-19 25 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

相關問題