简体   繁体   English

带有FileSystemWatcher的Windows Service在第一个事件后停止

[英]Windows Service with FileSystemWatcher stops after the first event

I'm building a simple Windows Service (basically combining this tutorial with this class ). 我正在构建一个简单的Windows服务(基本上将本教程此类结合)。

Now I have a "FROM" directory and two "TO" (TO1, TO2) directories. 现在,我有一个“ FROM”目录和两个“ TO”(TO1,TO2)目录。 When I place a file into FROM, it should be copied both to TO1 and TO2. 当我将文件放入FROM时,应将其同时复制到TO1和TO2。 I install the service and I start it in the Service Control Manager where I see it's running. 我安装了服务,并在运行状态的服务控制管理器中启动了该服务。 On the first run, it copies the file to TO1 and TO2 and the service is still running after that. 在第一次运行时,它将文件复制到TO1和TO2,并且此后服务仍在运行。 Then, when I place another file to FROM (with a different name), nothing happens. 然后,当我将另一个文件放置到FROM(具有不同的名称)时,什么也没发生。 And refreshing the services I find that the service stopped. 刷新服务后,我发现该服务已停止。

Why does the service stop? 服务为何停止​​? It seems it stops just in the moment when I place the second file. 似乎在我放置第二个文件的那一刻就停止了。

Here I register the file system watcher: 在这里,我注册了文件系统观察器:

    // File System Watcher
    var fileSystemWatcher = new FileSystemWatcher();
    fileSystemWatcher.Created += FileSystemWatcher_MoveOnCreate;
    fileSystemWatcher.Path = this.fromPath;
    fileSystemWatcher.EnableRaisingEvents = true;

And here is the event handler: 这是事件处理程序:

private void FileSystemWatcher_MoveOnCreate(object sender, FileSystemEventArgs e)
{
    string FROM = Path.Combine(fromPath, e.Name);
    string TO1 = Path.Combine(toPathOne, e.Name);
    string TO2 = Path.Combine(toPathTwo,  e.Name);

    File.Copy(FROM, TO1);
    File.Copy(FROM, TO2)
}

If the Windows Service stops there was an unhandled exception in your code somewhere. 如果Windows服务停止,则您的代码中某个地方将出现未处理的异常。 Try to surround the key point of your code ( maybe the entire body of the function FileSystemWatcher_MoveOnCreate ) with try{}catch(){} and log what's happening. 尝试使用try{}catch(){}包围代码的关键点(可能是FileSystemWatcher_MoveOnCreate函数的整个主体),并记录发生的情况。 In general you should add log to your windows service is the only way you can understand if things are going on anyway. 通常,您应该将日志添加到Windows服务中,这是您了解事情是否正在进行的唯一方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM