0

我創建了此Windows服務。我的老闆希望能夠通過在配置文件中使用appsettings來暫停它。它應該立即生效,而不必重新啓動服務。更改config-file中的設置,以便立即生效

在我的配置文件我有這樣的:

<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

ConfigurationManager類上有一個名爲RefreshSection的方法。

刷新指定的段以便下次檢索它時 將從磁盤重新讀取。

ConfigurationManager.RefreshSection("AppSettings"); 

的問題是,如果我理解正確的話,你設置讀它的服務超出這個新的價值。因此,在讀取值之前,您將被迫調用此RefreshSection,這可能是應用程序性能的一個問題。

+0

感謝這工作正常。 –

0

而且你必須將配置值設置爲零,否則它會再次暫停下一個循環。

+0

看起來您需要添加:「讀取暫停值後,應用程序應將值設置回零...」 – Artemix

相關問題