FileSystemWatcher:忽略自己的过程所做的更改

问题描述

我想问问是否有可能忽略内部的变化 自身进程FileSystemWatcher造成的文件系统更改事件 正在运行。 例如,我自己的进程在监视目录中创建一个文件, FileSystemWatcher应该认识到它是由进程创建的,或者 不要从一开始就引发事件。

解决方法

您可以使用应用程序要操作的文件列表:

{
    "Effect": "Allow","Action": "iam:CreateServiceLinkedRole","Resource": "*","Condition": {
        "StringEquals": {
            "iam:AWSServiceName": [
                "autoscaling.amazonaws.com","ec2scheduled.amazonaws.com","elasticloadbalancing.amazonaws.com","eks.amazonaws.com","eks-fargate-pods.amazonaws.com","eks-nodegroup.amazonaws.com","spot.amazonaws.com","spotfleet.amazonaws.com","transitgateway.amazonaws.com"
            ]
        }
    }
}
static private readonly List<string> WatcherFilesToIgnore = new List<string>();

因此,您在开始时编写的watcher事件处理程序中:

try
{
  WatcherFilesToIgnore.Add(filePath1);
  WatcherFilesToIgnore.Add(filePath2);
  // some file operation
}
finally
{
  WatcherFilesToIgnore.Remove(filePath1);
  WatcherFilesToIgnore.Remove(filePath2);
}

因此,当您的应用程序作用于某些文件时,观察者将不执行任何操作以使指定的内容忽略。

如果您使用多线程,请考虑使用一些同步。


如@CodeCaster所述,在应用程序和引发的Windows Shell事件之间可能存在滞后。

例如,可以简单地添加一个if ( WatcherFilesToIgnore.Contains(e.FullPath) ) return; // watcher process ,但这很危险。

因此,我们可以使用Sleep(2000)来指示该过程已终止,并让观察者自己清除列表:

Dictionary<string,bool>
WatcherFilesToIgnore.Add(filePath1,false);
// file operation
WatcherFilesToIgnore[filePath1] = true;

这仅在引发真正的观察者事件时才有效,否则文件将保留在列表中。

因此,我们需要确保在不执行任何操作的情况下,删除文件:

if ( WatcherFilesToIgnore.Contains(e.FullPath) ) 
{
  if ( WatcherFilesToIgnore[e.FullPath] )
    WatcherFilesToIgnore.Remove(e.FullPath);
  return;
}
// watcher process

WatcherFilesToIgnore.Add(filePath1,false); if ( ProcessFile(filePath1) ) WatcherFilesToIgnore[filePath1] = true; else WatcherFilesToIgnore.Remove(e.FullPath); 方法(我出于类似的解释考虑)执行所需的操作,如果成功完成某些更改,则返回true,否则返回false(未完成,引发异常,过程中止...)。