2016-05-23 60 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));