0

我创建了这个 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);
        }
    }

但我一定做错了什么,因为它没有再次读取设置。它只需要内存中的内容。

4

2 回答 2

2

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

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

 ConfigurationManager.RefreshSection("AppSettings");

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

于 2013-06-24T09:47:52.837 回答
0

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

于 2013-06-24T10:33:41.570 回答