更改配置文件中的设置,以便立即生效

时间:2013-06-24 09:43:06

标签: c# visual-studio-2012 windows-services application-settings

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

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

<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);
        }
    }

但我必须做错事,因为它不会再次读取设置。它只需要内存中的内容。

2 个答案:

答案 0 :(得分:2)

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

  

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

 ConfigurationManager.RefreshSection("AppSettings");

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

答案 1 :(得分:0)

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