C# FileSystemWatcher正在监视目录时正在等待
我正在尝试监视日志文件的更改。我的代码正在工作,并且做了它应该做的一切。但是,由于我希望它作为windows服务运行并不断监视,我不确定如何将其设置为等待状态。这是它目前正在做的事情C# FileSystemWatcher正在监视目录时正在等待,c#,logging,windows-services,filesystemwatcher,C#,Logging,Windows Services,Filesystemwatcher,我正在尝试监视日志文件的更改。我的代码正在工作,并且做了它应该做的一切。但是,由于我希望它作为windows服务运行并不断监视,我不确定如何将其设置为等待状态。这是它目前正在做的事情 public static void Main() { log_watcher = new FileSystemWatcher(); log_watcher.Path = Path.GetDirectoryName(pathToFile);
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服务中有什么更好的方法可以做到这一点?您可以使用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。这不是windows服务代码,只是一个控制台应用程序。首先创建一个正确的示例,其中有一个响应“开始”、“停止”等的消息泵(如winforms代码)。在我将代码放入服务之前@L.B尝试确保我的代码正常工作,因为它更容易调试,但控制台应用程序不是正确的测试方法。至少使用winforms appWhat在while(true)块中?这将利用100%的CPU。在Windows服务中,您只需在OnStart方法中初始化FileSystemWatcher,而不执行其他操作。然后服务正在运行,等待事件,占用0%的CPU