我正在将 filesystemwatcher 用于将在框架 1.1 上运行的程序,并且当发生更改时,它会发送 2 个信号说它已更改。通过研究,我知道这就是 Windows 的工作方式,我无法用 fsw 阻止这种情况。
但作为一种解决方法,我想让它接受第一个脉冲,然后锁定,所以另一个试图调用该方法的方法被忽略(或重定向?),因为我有一个备份系统,它是制作所有文件的 2 个副本,所以这是我真正需要解决的问题。代码的其他地方受到影响,我已经设法使用定时器来解决这个问题,方法是在调用定时器时立即阻止它,但是在这种情况下它会变得非常混乱,我相信必须有一个更清洁的解决方案。
代码:
private static void GetCurrentJob()
{
///Lots of code that isn't relevant
}
private static void ProgramSwapMonitor(string ProgramChange)
{
// Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher
{
Path = ProgramChange,
/* Watch for changes in LastAccess and LastWrite times, and
the renaming of files or directories. */
NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName,
// Only watch this specific file
Filter = "dnocontainer.cfg"
};
// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
// Begin watching.
watcher.EnableRaisingEvents = true;
}
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
//This disables the directory monitor, then changes the active job in its memory, then restarts the directory monitor so it can now monitor the new location, then removes the old watcherChanged instance so theres no duplicates.
fileSystemWatcher.EnableRaisingEvents = false;
GetCurrentJob(); //This is the method that needs to be only running once, but is made to run twice
MonitorDirectory(path);
fileSystemWatcher.Changed -= new FileSystemEventHandler(FileSystemWatcher_Changed);
}