更改配置文件中的设置,使其立即生效

本文关键字:配置文件 设置 | 更新日期: 2023-09-27 18:19:35

我创建了这个windows服务。我的老板希望能够通过在配置文件中使用appsettings来暂停它。它应该立即生效,而无需重新启动服务。

在我的配置文件中,我有这样的:

<appSettings>
    <!-- If you want the DIS to pause for a while, give a valid number here.
    The value should be provided in minutes.-->     
    <add key="PauseDis" value="5"/>
</appSettings>

在我的代码中,我正在执行以下操作:

protected override void OnStart(string[] args)
    {
        thread = new Thread(WorkerThreadFunc);
        thread.Name = "Indigo.DataIntakeService Thread";
        thread.IsBackground = true;
        thread.Start();
    }
private void WorkerThreadFunc()
    {
        while (!shutdownEvent.WaitOne(0))
        {
            CheckFolders(toCheckFolders);
        }
    }private void CheckFolders(FoldersConfigSection folder)
    {
        using (FolderActions folderActions = new FolderActions())
        {
            PauseWorking();
            folderActions.DestinationFolders = (FoldersConfigSection)ConfigurationManager.GetSection("DestinationFolders");
            folderActions.BackUpFolders = (FoldersConfigSection)ConfigurationManager.GetSection("BackUpFolders");
            folderActions.TriggerName = ConfigurationManager.AppSettings["Trigger"];
            foreach (FolderElement folderElement in folder.FolderItems)
            {
                folderActions.SearchDirectoryAndCopyFiles(folderElement.Path, ConfigurationManager.AppSettings["Environment"]);
            }
        }
    }
    private void PauseWorking()
    {
        this.pauseTime = Convert.ToInt16(ConfigurationManager.AppSettings["PauseDis"]);
        LogManager.LogWarning(String.Format("PauseTime => {0}", this.pauseTime));
        if (this.pauseTime != 0)
        {
            // A pause was provided in the config-file, so we pause the thread.
            // The pause-time is provided in minutes. So we convert it to mil!iseconds.
            // 1 minute = 60 000 milliseconds
            LogManager.LogWarning(String.Format(Resources.WARN_ThreadSleeping, this.pauseTime));
            Thread.Sleep(this.pauseTime * 60000);
        }
    }

但我一定是做错了什么,因为它没有重新读取设置。它只需要记忆中的东西。

更改配置文件中的设置,使其立即生效

ConfigurationManager类上有一个名为RefreshSection的方法。

刷新命名节,以便下次检索它时将从磁盘中重新读取。

 ConfigurationManager.RefreshSection("AppSettings");

如果我理解正确的话,问题是你在读取该值的服务之外设置了这个新值。因此,你将被迫在读取值之前调用这个RefreshSection,这可能会对你的应用程序的性能造成问题。

您必须将配置值设置为零,否则它将在下一个循环中再次暂停。