文件系统监视器跳过了一些事件。

9
如果你搜索 FileSystemWatcher 的问题,你会发现很多关于 FileSystemWatcher 跳过某些事件(未触发所有事件)的文章。基本上,如果你在监视的文件夹中更改了很多文件,其中一些文件将不会被 FileSystemWatcher 处理。
为什么会这样,我该如何避免错过事件?

它不会跳过事件。不为Error事件编写事件处理程序是你的错误。没有其他方法可以发现你的事件处理程序太慢和/或需要增加InternalBufferSize。此外,它无法解决你在事件处理程序中使用try/catch来忽略IOException的问题,该异常告诉你文件尚未打开。 - Hans Passant
当然你需要一个错误事件处理程序。我的代码仅演示了文件更改检测和文件处理在两个线程中的分离。我也没有编写代码来检测创建它的进程是否已释放文件。该代码应该在ProcessFile函数中,正如我在代码中所注释的那样。 - dok
1个回答

13

原因

FileSystemWatcher正在监视某个文件夹中发生的更改。当文件被更改时(例如文件被创建),FileSystemWatcher会触发相应的事件。事件处理程序可以解压缩文件,读取其内容以确定如何进一步处理它,在数据库日志表中写入记录并将文件移动到另一个文件夹。文件的处理可能需要一些时间。

在此期间,可能会在所监视的文件夹中创建另一个文件。由于FileSystemWatcher的事件处理程序正在处理第一个文件,因此无法处理第二个文件的创建事件。因此,FileSystemWatcher会错过第二个文件。 enter image description here

解决方案

由于文件处理可能需要一些时间,并且其他文件的创建可能无法被FileSystemWatcher检测到,因此应该将文件处理与文件更改检测分开,并且文件更改检测应该非常短,以便它永远不会错过单个文件更改。文件处理可以分成两个线程:一个用于文件更改检测,另一个用于文件处理。当文件被更改并且被FileSystemWatcher检测到时,适当的事件处理程序应仅读取其路径,将其转发到文件处理线程并关闭本身,以便FileSystemWatcher可以检测到另一个文件更改并使用相同的事件处理程序。处理线程可以花费任意时间来处理该文件。队列用于将文件路径从事件处理程序线程转发到处理线程。 enter image description here

这是经典的生产者-消费者问题。有关生产者-消费者队列的更多信息,请参见此处

代码

using System;
using System.IO;
using System.Threading;
using System.Collections.Generic;

namespace FileSystemWatcherExample {
    class Program {
        static void Main(string[] args) {
            // If a directory and filter are not specified, exit program
            if (args.Length !=2) {
                // Display the proper way to call the program
                Console.WriteLine("Usage: Watcher.exe \"directory\" \"filter\"");
                return;
            }

            FileProcessor fileProcessor = new FileProcessor();

            // Create a new FileSystemWatcher
            FileSystemWatcher fileSystemWatcher1 = new FileSystemWatcher();

            // Set FileSystemWatcher's properties
            fileSystemWatcher1.Path = args[0];
            fileSystemWatcher1.Filter = args[1];
            fileSystemWatcher1.IncludeSubdirectories = false;

            // Add event handlers
            fileSystemWatcher1.Created += new System.IO.FileSystemEventHandler(this.fileSystemWatcher1_Created);

            // Start to watch
            fileSystemWatcher1.EnableRaisingEvents = true;

            // Wait for the user to quit the program
            Console.WriteLine("Press \'q\' to quit the program.");
            while(Console.Read()!='q');

            // Turn off FileSystemWatcher
            if (fileSystemWatcher1 != null) {
                fileSystemWatcher1.EnableRaisingEvents = false;
                fileSystemWatcher1.Dispose();
                fileSystemWatcher1 = null;
            }

            // Dispose fileProcessor
            if (fileProcessor != null)
                fileProcessor.Dispose();
        }

        // Define the event handler
        private void fileSystemWatcher1_Created(object sender, FileSystemEventArgs e) {
            // If file is created...
            if (e.ChangeType == WatcherChangeTypes.Created) {
                // ...enqueue it's file name so it can be processed...
                fileProcessor.EnqueueFileName(e.FullPath);
            }
            // ...and immediately finish event handler
        }
    }


    // File processor class
    class FileProcessor : IDisposable {
        // Create an AutoResetEvent EventWaitHandle
        private EventWaitHandle eventWaitHandle = new AutoResetEvent(false);
        private Thread worker;
        private readonly object locker = new object();
        private Queue<string> fileNamesQueue = new Queue<string>();

        public FileProcessor() {
            // Create worker thread
            worker = new Thread(Work);
            // Start worker thread
            worker.Start();
        }

        public void EnqueueFileName(string FileName) {
            // Enqueue the file name
            // This statement is secured by lock to prevent other thread to mess with queue while enqueuing file name
            lock (locker) fileNamesQueue.Enqueue(FileName);
            // Signal worker that file name is enqueued and that it can be processed
            eventWaitHandle.Set();
        }

        private void Work() {
            while (true) {
                string fileName = null;

                // Dequeue the file name
                lock (locker)
                    if (fileNamesQueue.Count > 0) {
                        fileName = fileNamesQueue.Dequeue();
                        // If file name is null then stop worker thread
                        if (fileName == null) return;
                    }

                if (fileName != null) {
                    // Process file
                    ProcessFile(fileName);
                } else {
                    // No more file names - wait for a signal
                    eventWaitHandle.WaitOne();
                }
            }
        }

        private ProcessFile(string FileName) {
            // Maybe it has to wait for file to stop being used by process that created it before it can continue
            // Unzip file
            // Read its content
            // Log file data to database
            // Move file to archive folder
        }


        #region IDisposable Members

        public void Dispose() {
            // Signal the FileProcessor to exit
            EnqueueFileName(null);
            // Wait for the FileProcessor's thread to finish
            worker.Join();
            // Release any OS resources
            eventWaitHandle.Close();
        }

        #endregion
    }
}

2
有趣。这里是关于丢失更改的文档:https://msdn.microsoft.com/zh-cn/library/system.io.filesystemwatcher(v=vs.110).aspx?f=255&MSPPError=-2147217396#Anchor_6 。"Windows操作系统通过FileSystemWatcher创建的缓冲区通知您的组件文件的更改。如果在短时间内有很多更改,缓冲区可能会溢出。这会导致组件无法跟踪目录中的更改,并且只会提供总体通知。" - Jacob
1
我怀疑对大多数用例来说,这段代码应该可以防止内部缓冲区溢出。只要事件处理程序能够比输入事件更快地处理它们,内部缓冲区就不应该会溢出。 - Eric J.
1
Eric J. 是正确的。这种解决方案不适用于在短时间内有许多更改和缓冲区溢出的情况。这适用于两个文件之间的更改时间比处理第一个文件的时间更短的情况。在处理第一个文件时,第二个文件发生变化,因此事件处理程序无法处理它。如果 FSW 在长时间内监视了大量的更改,那么您肯定会遇到这个问题。 - dok
1
为什么某些东西会丢失而不排队,这对我来说没有任何意义。当V8忙碌时,它也不会简单地丢弃事件吗? - Ini
它被排队到缓冲区,但是缓冲区很小,当短时间内有数百个事件同时发生时,可能会溢出,而事件处理程序正在运行。事件处理程序将阻塞引发事件的对象。 - Welcor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接