它会在首次访问属性时被缓存,因此每次请求值时它都不会从物理文件中读取。这就是为什么必须重新启动 Windows 应用程序(或 Refresh 配置)以获取最新值,以及为什么 ASP.Net 应用程序在您编辑 web.config 时自动重新启动的原因。答案 How to prevent an ASP.NET application restarting when the web.config is modified 中的参考资料讨论了为什么 ASP.Net 硬连线重启。
我们可以使用ILSpy 验证这一点并查看 System.Configuration 的内部结构:
public static NameValueCollection AppSettings
{
get
{
object section = ConfigurationManager.GetSection("appSettings");
if (section == null || !(section is NameValueCollection))
{
throw new ConfigurationErrorsException(SR.GetString("Config_appsettings_declaration_invalid"));
}
return (NameValueCollection)section;
}
}
起初,这确实看起来每次都会获取该部分。查看 GetSection:
public static object GetSection(string sectionName)
{
if (string.IsNullOrEmpty(sectionName))
{
return null;
}
ConfigurationManager.PrepareConfigSystem();
return ConfigurationManager.s_configSystem.GetSection(sectionName);
}
这里的关键线是PrepareConfigSystem()方法;这会初始化 ConfigurationManager 持有的 IInternalConfigSystem 字段的实例 - 具体类型是 ClientConfigurationSystem
作为此负载的一部分,Configuration 类的实例被实例化。此类实际上是配置文件的对象表示,并且似乎由静态字段中的 ClientConfigurationSystem 的 ClientConfigurationHost 属性持有 - 因此它被缓存。
您可以通过执行以下操作(在 Windows 窗体或 WPF 应用程序中)凭经验对此进行测试:
- 启动您的应用程序
- 访问 app.config 中的值
- 更改 app.config
- 检查新值是否存在
- 致电
ConfigurationManager.RefreshSection("appSettings")
- 检查是否存在新值。
事实上,如果我只是阅读关于 RefreshSection 方法的评论,我本可以为自己节省一些时间 :-)
/// <summary>Refreshes the named section so the next time that it is retrieved it will be re-read from disk.</summary>
/// <param name="sectionName">The configuration section name or the configuration path and section name of the section to refresh.</param>