//这是读取配置文件(BaseConfig.config)的方法
//通过序列化和反序列进行读写
public static BaseConfig getModel()
        {
            WebConfig = HttpContext.Current.Cache["SystemBaseConfig"] as BaseConfig;
            if (WebConfig == null)
            {
                string path = Lib.GetMapPath(ConfigurationManager.AppSettings["WebBaseConfig"].ToString());
                //创建缓存依赖项
                CacheDependency dependency = new CacheDependency(path);
                HttpContext.Current.Cache.Add("SystemBaseConfig", (BaseConfig)SerializationHelper.Load(typeof(BaseConfig), path), dependency, Cache.NoAbsoluteExpiration, new TimeSpan(0, 30, 0), CacheItemPriority.Default, null);
                WebConfig = HttpContext.Current.Cache["SystemBaseConfig"] as BaseConfig;
            }
            return WebConfig;
}
// 这是进行保存的
private static object lockHelper = new object();        public void Save(BaseConfig model,string path)
        {
            lock (lockHelper)
            {
                SerializationHelper.Save(model, path);
            }
        }//调用保存的方法是
new BLLBaseConfig().Save(model, Server.MapPath(ConfigurationManager.AppSettings["WebBaseConfig"].ToString()));
现在的问题是:保存时能正确写入.config文件,读取时并不会读取更新后的文件。
查了MSDN上关于CacheDependency dependency = new CacheDependency(path);的解释,说是当里面的对象被修改时会自动的移除该项。
那这说法应该是当我保存时HttpContext.Current.Cache["SystemBaseConfig"]这个缓存就为空了,可我刷新时还是读取缓存中的。
不知是不是哪里写错了。

解决方案 »

  1.   

    Cache保存的对象必须通过重新赋值来更新
      

  2.   

    谢谢foren_whb
    这段代码是从dtcms里面看到的,它在保存时并没有重新赋值到cache中。
    如果保存后要重新赋值的话,那
    CacheDependency dependency = new CacheDependency(path);
    这一句的意思就不是当里面的内容被更改时,会自动更新了。
      

  3.   

    谢谢,看了上面的帖子,还是找不出哪里出错了。
    我上面的代码哪里出错了呢,依赖缓存最重要的就是设置这里吧  CacheDependency dependency = new CacheDependency(path);
                    HttpContext.Current.Cache.Add("SystemBaseConfig", (BaseConfig)SerializationHelper.Load(typeof(BaseConfig), path), dependency, Cache.NoAbsoluteExpiration, new TimeSpan(0, 30, 0), CacheItemPriority.Default, null);
                   
      

  4.   

    Cache不同于普通的存储结构,
    它必须维护其即时与准确性.
    其内容一旦被修改,
    则意味着Cache数据出错,
    系统会自动清除错误数据,
    避免出现更严重的业务问题.因此修改后的缓存对象必须重新赋值给Cache,
    让系统明白这是有意为之.