1

我正在建立一个系统来监视图像目录然后处理它们。

有时 PDF 可能会被放入监视的目录中,在这种情况下,我将它们转换为图像并照常继续。

但是,一旦图像被处理,它就会将其移动到一个完整的文件夹中,但如果 PDF 到图像的转换不完整,那么我的代码将引发 IO 异常,因为它无法移动另一个进程正在使用的文件。

是否可以指定通知过滤器仅处理“完整”文件。完成是指它已完成复制、移动或创建。

我猜测发生这种冲突是因为处理文件的工作人员在不同的线程上运行。

public void Start()
{
  if (string.IsNullOrWhiteSpace(this.fileDirectory))
  {
    throw new Exception("No file directory specified.");
  }

  // watch for any type of file activity
  const NotifyFilters Filters = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.CreationTime;

  // set up the watcher based on the app.config file
  var watcher = new FileSystemWatcher() { Path = this.fileDirectory, NotifyFilter = Filters, EnableRaisingEvents = true };

  // event handler for new files
  watcher.Created += this.NewFileCreated;

  // file system watcher doesn't "see" current files, manually get these
  this.ProcessExistingFiles();
}

private void NewFileCreated(object source, FileSystemEventArgs e)
{
  Task.Run(() => this.ProcessFile(e.FullPath));
}

private void ProcessExistingFiles()
{
  var files = Directory.GetFiles(this.fileDirectory);
  Parallel.ForEach(files, this.ProcessFile);
}
4

2 回答 2

0

据我了解,您有两种类型的文件到达受监控的目录:图像和 pdf。如果 pdf 到达,您必须先将其转换为图像。我不确定您描述的异常的原因是什么 - 转换和处理(最终移动)是否同时完成?

如果不是 - 你找错地方了。可能首先将文件放在那里的进程仍然持有它的句柄。

如果答案是肯定的,那么我有两个建议:

  1. 将pdf文件放入不同的文件夹。转换过程将收听此文件夹,并在提取图像后立即进行移动。这样,您不需要更改当前算法中的任何内容,只需添加另一个隔离级别。

  2. Alternatively, you can set a filter on the FSW to monitor only image files (filter file extension) this way, when a pdf is put to the directory, it does not go straight away to processing, it first gets converted to an image. At the end of the conversion, the monitored directory suddenly "receives" another another image! And the process continues as normal. This is essentially another way to receive isolation between the images and the pdfs.

于 2012-07-24T10:18:07.613 回答
0

Possibly, you can try to lock files for writing, if this operation fails - file not completed - wait some time (for next changes or 1 second, for example).

于 2012-07-24T10:22:51.800 回答