2017-10-25 18 views
-1

변경 사항에 대한 로그 파일을 모니터링하려고합니다. 내 코드가 작동하며 필요한 모든 작업을 수행합니다. 그러나, 나는 이것을 Windows 서비스로 실행하고 끊임없이 모니터링하고 싶기 때문에 대기 상태로 설정하는 적절한 방법을 확신하지 못합니다. 여기에 그것이 지금하고있는 일입니다.FileSystemWatcher가 디렉토리를 모니터링하는 동안 대기 중

public static void Main() 
    { 
      log_watcher = new FileSystemWatcher(); 
      log_watcher.Path = Path.GetDirectoryName(pathToFile); 
      log_watcher.Filter = recent_file.Name; 
      log_watcher.NotifyFilter = NotifyFilters.LastWrite; 
      log_watcher.Changed += new FileSystemEventHandler(OnChanged); 

      log_watcher.EnableRaisingEvents = true; 
      //do rest of stuff OnChanged 
      while (true) 
      { 

      } 
    } 

그리고 그냥 간단 :

public static void OnChanged(object sender, FileSystemEventArgs e) 
    { 
     Console.WriteLine("File has changed"); 
    } 

어떤이 할 수있는 Windows 서비스에 더 나은 방법이 될 것입니다?

+0

Windows 서비스 코드가 아니라 콘솔 앱입니다. 먼저 "시작", "중지"등에 응답하는 메시지 펌프 (예 : winforms 코드)가있는 정확한 샘플을 만듭니다. –

+0

@LB 코드를 사용하기 전에 코드가 작동하는지 확인하기가 더 쉽기 때문에 debug imo – Tom

+0

하지만 콘솔 앱은 테스트하기에 옳지 않습니다. 적어도 winforms 앱을 사용하십시오 –

답변

0

WinForms의 Application.Run()을 사용하여 메시지 펌프를 시작할 수 있습니다.

using System.Windows.Forms; 
// The class that handles the creation of the application windows 
class MyApplicationContext : ApplicationContext { 

    private MyApplicationContext() { 
     // Handle the ApplicationExit event to know when the application is exiting. 
     Application.ApplicationExit += new EventHandler(this.OnApplicationExit); 

     log_watcher = new FileSystemWatcher(); 
     log_watcher.Path = Path.GetDirectoryName(pathToFile); 
     log_watcher.Filter = recent_file.Name; 
     log_watcher.NotifyFilter = NotifyFilters.LastWrite; 
     log_watcher.Changed += new FileSystemEventHandler(OnChanged); 

     log_watcher.EnableRaisingEvents = true; 
    } 

    public static void OnChanged(object sender, FileSystemEventArgs e) { 
     Console.WriteLine("File has changed"); 
    } 

    private void OnApplicationExit(object sender, EventArgs e) { 
     Console.WriteLine("File monitor exited."); 
    } 

    [STAThread] 
    static void Main(string[] args) { 

     // Create the MyApplicationContext, that derives from  ApplicationContext, 
     // that manages when the application should exit. 

     MyApplicationContext context = new MyApplicationContext(); 

     // Run the application with the specific context. It will exit when 
     // all forms are closed. 
     Application.Run(context); 

    } 
} 

docs.microsoft.com의 Run(ApplicationContext)을 참조하십시오.