【发布时间】:2014-05-21 19:34:53
【问题描述】:
我有一个使用 C# 编写的 Windows 服务。在幕后它是一个 FileSystemWatcher。 FSW 查找新文件并相应地处理它们。当我的服务启动时,它还需要处理现有文件。当我通过控制台应用程序执行此操作时,一切都按预期工作。
但是,当我尝试将这一切包装在 Win 服务中时,我的第一个问题是 Win 服务无法启动。超时是因为,即使最初要处理的文件很多,但处理时间太长。
这是我的“观看”类的部分代码:
public WatcherService()
{
_log.Debug("WatcherService instantiated.");
_watcher = new FileSystemWatcher { Path = AppConfig.MonitorFolder, IncludeSubdirectories = true };
// we want the watching to start BEFORE we process existing files
// because if we do it the other way, a file might get missed
_watcher.Created += File_OnChanged;
}
public void StartWatching()
{
_log.Debug("WatcherService started.");
// this kicks off the watching
_watcher.EnableRaisingEvents = true;
// process existing files
ProcessExistingFiles(AppConfig.MonitorFolder);
}
我的解决方法是启动 FSW“监视”并在单独的异步线程上处理初始文件,如下所示(在我的 Windows 服务代码中):
protected override void OnStart(string[] args)
{
_log.Debug("LoggingService starting.");
// kick off the watcher on another thread so that the OnStart() returns faster;
// otherwise it will hang if there are a lot of files that need to be processed immediately
Task.Factory.StartNew(() => _watcher.StartWatching()).ContinueWith(t =>
{
if (t.Status == TaskStatus.Faulted)
{
_log.Error("Logging service failed to start.", t.Exception.InnerException ?? t.Exception);
}
});
}
如果我没有在 Task.Factory.StartNew() 中包装那个“StartWatching”方法,OnStart() 就会超时,这是可以理解的。但现在看来我的 StartWatching() 方法从未被调用过。我在日志中看到“LoggingService 启动”,但没有看到“WatcherService 启动”。 (编辑:仅供参考,我也尝试过 Task.Run(),但无济于事。)
那是怎么回事?我确定我要么不明白 StartNew() 在做什么和/或有更好的方法来完成我想要完成的工作。
想法?
谢谢!
【问题讨论】:
-
尝试使用不同的条件语句,看看输出是什么(如果你还没有尝试过)。
标签: c# filesystemwatcher