6

我有以下代码来缓存一些昂贵的代码。

  private MyViewModel GetVM(Params myParams)
    {
        string cacheKey = myParams.runDate.ToString();
        var cacheResults = HttpContext.Cache[cacheKey] as MyViewModel ;
        if (cacheResults == null)
        {
            cacheResults = RunExpensiveCodeToGenerateVM(myParams);
            HttpContext.Cache[cacheKey] = cacheResults;
        }                
   return cacheResults;
   }

这会永远留在缓存中吗?直到服务器重新启动或内存不足?

4

1 回答 1

5

这会永远留在缓存中吗?

这将取决于您使用的特定缓存提供程序。例如,如果您使用默认的内存缓存,则如果服务器开始内存不足或应用程序池被回收,它可能会过期。但是,如果您正在使用其他一些缓存提供程序,例如分布式缓存,memcached或者AppFactory这将取决于特定的实现。

经验法则是永远不要假设某些东西在缓存中,因为您之前存储了它。始终首先检查缓存中是否存在该项目,如果不存在,则获取它并再次存储在缓存中。

于 2011-06-30T11:18:03.380 回答