代码之家  ›  专栏  ›  技术社区  ›  Pretzel

ASP.NET:HttpRuntime.Cache在保存WebConfigurationManager时被刷新-这是个错误吗?

  •  1
  • Pretzel  · 技术社区  · 15 年前

    HttpRuntime.Cache 通常我的印象是,如果我在缓存中“添加”了如下内容:

    HttpRuntime.Cache.Insert("Test", "This is a test!", null, 
         Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, 
         CacheItemPriority.NotRemovable, new CacheItemRemovedCallback(FileChanged));
    

    “NotRemovable”和“NoExpiration”标志将在应用程序期间将对象保留在内存中。但是发现在某些页面请求的末尾,HttpRuntime.Cache将完全为空!

    最后,我评论道:

    WebConfigurationManager.OpenWebConfiguration("~").Save;
    

    我主要是从AppSettings区域的“web.config”中检索数据,但偶尔会写回AppSettings并使用上面的命令保存更改。我从阅读中知道“web.config”是缓存的,但是将我的更改保存回它不应该刷新所有的HttpRuntime.Cache,对吧?

    这是虫子吗?或者这两个缓存是以某种方式联系在一起的,我应该知道吗?

    编辑:

    HomeController 无论已经存在什么:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Configuration;
    using System.Configuration;
    
    namespace BackButtonTest.Controllers
    {
        [HandleError]
        public class HomeController : Controller
        {
            private string MESSAGE = "Message";
            public ActionResult Index()
            {
                ViewData[MESSAGE] = HttpRuntime.Cache.Get(MESSAGE);
                Configuration Config = WebConfigurationManager.OpenWebConfiguration("~");
                Config.AppSettings.Settings.Add("SomeKey", "SomeValue");
                Config.Save();
                return View();
            }
    
            public ActionResult About()
            {
                HttpRuntime.Cache[MESSAGE] = "This is pulled from the HttpRuntime.Cache";
                return View();
            }
        }
    }
    

    1. 在调试模式下启动应用程序。
    2. 点击“关于”链接。这会将字符串加载到缓存中。
    3. 点击“主页”链接。字符串从缓存中提取并卡在ViewMessage字典中。一些键/值对写入web.config并保存。缓存中的字符串应出现在主页上。
    4. 再次单击“主页”链接。字符串 从缓存中提取,但不是。
    5. 停止程序。注释掉以“Config”开头的3行。重新启动程序。
    6. 再次尝试步骤1到4。注意HttpRuntime.Cache没有清空。

    1 回复  |  直到 15 年前
        1
  •  2
  •   Onkelborg    15 年前

    写入web.config将强制应用程序重新启动,而且,最有可能的是,清空缓存、进程内会话状态等事件将关闭。尝试在global.asax Application_End中写下一些日志(或者方法的名称是:)

    推荐文章