它缓存,在性能的第一次访问,所以它不会从物理文件中的每个你问一个值时读取。这就是为什么有必要重新启动Windows应用程序(或配置Refresh)以获取最新值,以及为什么在编辑web.config时ASP.Net应用程序会自动重新启动。为什么ASP.Net硬连线重启在回答How to prevent an ASP.NET application restarting when the web.config is modified的参考文献中讨论。
我们可以验证这一点使用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>
你是什么意思的“不总是”!这是设计我已经理解,IIS重新启动应用程序并重新加载配置。 –