app.config的设置何时实际由应用程序读取?
假设我有一个Windows服务和一些应用程序设置.在代码中我有一个方法,其中使用了一些设置.在每次迭代中调用方法,而不是在所有时间内调用一次.如果我通过配置文件更改设置值,我是否应重新启动服务以使其在内部“刷新”,或者在下次没有任何交互的情况下接受它?
解决方法
您需要调用
ConfigurationManager.RefreshSection方法以获取直接从磁盘读取的最新值.这是测试和回答问题的简单方法:
static void Main(string[] args)
{
while (true)
{
// There is no need to restart you application to get latest values.
// Calling this method forces the reading of the setting directly from the config.
ConfigurationManager.RefreshSection("appSettings");
Console.WriteLine(ConfigurationManager.AppSettings["myKey"]);
// Or if you're using the Settings class.
Properties.Settings.Default.Reload();
Console.WriteLine(Properties.Settings.Default.MyTestSetting);
// Sleep to have time to change the setting and verify.
Thread.Sleep(10000);
}
}
我的app.config包含:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup,System,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089" >
<section name="ConsoleApplication2.Properties.Settings" type="System.Configuration.ClientSettingsSection,PublicKeyToken=b77a5c561934e089" allowExeDeFinition="MachinetoLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<appSettings>
<add key="myKey" value="Original Value"/>
</appSettings>
<userSettings>
<ConsoleApplication2.Properties.Settings>
<setting name="MyTestSetting" serializeAs="String">
<value>Original Value</value>
</setting>
</ConsoleApplication2.Properties.Settings>
</userSettings>
</configuration>
启动应用程序后,打开build文件夹中的app.config,然后更改appSetting“myKey”的值.您将看到打印到控制台的新值.
要回答这个问题,是的,我们会在第一次读取它们时缓存它们,并且要从磁盘强制读取,您需要刷新该部分.