【发布时间】:2016-03-30 02:54:55
【问题描述】:
背景: 我正在使用 Timer 在 Windows 服务中定期做一些工作。我希望 Timer 在运行时可配置。我唯一能做的就是在启动时对其进行配置。
我的解决方案: 我正在使用 app.config 来配置计时器的开始时间和周期:
<appSettings>
<add key="StartTime" value="14:40:00"/>
<add key="Period" value="24:00:00"/>
</appSettings>
我正在使用 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;
}
}
最后,每个监听器都会像这样得到它的配置:
public void NotifyConfigurationChanged()
{
string strKeyName = "StartTime";
string startTime = ConfigurationManager.AppSettings[strKeyName];
// ...
}
还有问题: - 当我编辑文件时,文件观察器会触发事件,但是当我尝试获取新的 AppSettings 时,我正在读取旧值(从服务启动时开始)
奇怪的是,这个设置在某些时候有效,然后它没有(据我所知,没有更改代码)。
非常感谢任何帮助/建议。
【问题讨论】:
-
您好,感谢您的回复!我检查了该主题,但没有有用的信息来解决我的问题
标签: c#