背景:我使用计时器在 Windows 服务中定期执行一些工作。我希望计时器可以在运行时进行配置。我唯一能做的就是在启动时配置它。
我的解决方案:我使用 app.config 来配置计时器的开始时间和周期:
<appSettings>
<add key="StartTime" value="14:40:00"/>
<add key="Period" value="24:00:00"/>
</appSettings>
Run Code Online (Sandbox Code Playgroud)
我正在使用 FileSystemWatcher 来通知配置文件上的文件写入(将是 AppName.exe.config)
public ConfigWatcher(params object[] args)
{
configurationChangedListeners = new List<INotifyConfigurationChanged>();
string assemblyDirectory = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
NotifyFilters notifyFilters = NotifyFilters.LastWrite;
_fileSystemWatcher = new FileSystemWatcher()
{
Path = assemblyDirectory,
NotifyFilter = notifyFilters,
Filter = "*.config"
};
_fileSystemWatcher.Changed += OnChanged;
_fileSystemWatcher.EnableRaisingEvents = true;
if (args != null)
{
foreach (var arg in args)
{
AddListener(arg);
}
}
}
private void OnChanged(object source, System.IO.FileSystemEventArgs e)
{
try
{
_fileSystemWatcher.EnableRaisingEvents = false;
ConfigurationManager.RefreshSection("appSettings");
foreach (var listener in configurationChangedListeners)
{
listener.NotifyConfigurationChanged();
}
}
finally
{
_fileSystemWatcher.EnableRaisingEvents = true;
}
}
Run Code Online (Sandbox Code Playgroud)
最后,每个侦听器都会像这样获取其配置:
public void NotifyConfigurationChanged()
{
string strKeyName = "StartTime";
string startTime = ConfigurationManager.AppSettings[strKeyName];
// ...
}
Run Code Online (Sandbox Code Playgroud)
问题是:-当我编辑文件时,文件观察器会触发事件,但是当我尝试获取新的 AppSettings 时,我正在读取旧值(从服务启动时开始)
奇怪的是,在某些时候这个设置起作用了,然后就不起作用了(据我所知,没有更改代码)。
非常感谢任何帮助/建议。
问题的答案(经过大量搜索:D)是使用 OpenExeConfiguration 而不是直接访问 AppSettings。据我了解,刷新后需要再次打开配置:
var appSettings = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetEntryAssembly().Location).AppSettings;
string setting = appSettings.Settings[strKeyName].Value;
Run Code Online (Sandbox Code Playgroud)
我确信,当我第一次尝试时,第一个变体在某种情况下有效......