2016-05-23 62 views
2

我下面的代碼有問題。我有以下代碼,HttpRuntime.Cache沒有過期?

  if (HttpRuntime.Cache[cacheKey] == null) 
      { 
       AddTask(cacheKey, JsonConvert.SerializeObject(result), 60 * 30); 
      } 
      r = JsonConvert.DeserializeObject<Result>(HttpRuntime.Cache[cacheKey].ToString()); 
      HttpRuntime.Cache[cacheKey] = JsonConvert.SerializeObject(r); 


      private static void AddTask(string key, string value, int seconds) 
      { 
       HttpRuntime.Cache.Insert(key, value, null, 
        DateTime.Now.AddSeconds(10), Cache.NoSlidingExpiration, 
        CacheItemPriority.NotRemovable, new CacheItemRemovedCallback(CacheItemRemoved)); 
      } 

    public static void CacheItemRemoved(string k, object v, CacheItemRemovedReason r) 
    { 
    } 

我在做什麼只是添加和更新(如果存在)緩存。然後10秒後我想檢查一下。但我的CacheItemRemoved回調從未調用過。

+0

不保證該項目將被刪除 - 這不是一個緩存點。你想在這裏做什麼? – Luaan

+0

添加和更新緩存中的項目。並在一段時間後,我想刪除緩存並在回調中保存所有緩存數據。 – SAL

+0

好吧,'Cache'不會爲此工作。首先,它並不能保證你的物品被刪除,而且兩次,它不能保證當物品*被移除時,該回調被調用並結束執行。它是一個緩存,而不是寫緩衝區 - 如果你需要一個寫緩衝區,你需要自己做一個。 – Luaan

回答

1

當過更新使用

HttpRuntime.Cache[cacheKey] = JsonConvert.SerializeObject(r); 

則緩衝時間重置爲默認時間的高速緩存。現在,而不是使用字符串,現在我用對象實例,而不更新緩存。工作

notification = HttpRuntime.Cache[cacheKey] as Notification; 
HttpRuntime.Cache.Insert(key, notificationResult , null, 
       DateTime.Now.AddSeconds(10), Cache.NoSlidingExpiration, 
       CacheItemPriority.NotRemovable, new CacheItemRemovedCallback(CacheItemRemoved));