c# - FileSystemWatcher - 事件没有触发第二次

标签 c# filesystemwatcher

我有一个启动其他应用程序的应用程序,然后等待它们创建一个特定的数据文件(它一次监视一个应用程序)。每次启动应用程序时,它都会监视特定目录以查找要创建的特定文件。我正在使用 FileSystemWatcher 来执行此操作(将其设置为目录,然后过滤以获取正确的文件名)。第一次(总是)效果很好,但启动的第二个应用程序从未触发事件。它似乎触发事件的唯一方法是在事件处理程序中放置一个断点,或者在事件处理程序中有一个 Thread.Sleep 命令。这对我来说似乎很奇怪......是否有一些我不知道的竞争条件?这是代码。注意我有一个 Thread.Sleep(500)。使用这一行,代码每次都有效。没有它就会失败。我真的不愿意依赖 Sleep 命令。我不确定什么情况会导致它无法正常工作。

    public static void watchFiles(string path)
    {
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = path;
        watcher.Created += new FileSystemEventHandler(watcher_Handler);
        watcher.EnableRaisingEvents = true;
   }

    public static void watcher_Handler(object sender, FileSystemEventArgs e)
    {
        //Hack - the sleep allows the second and third application to be caught by this event
        Thread.Sleep(500);

        switch (e.ChangeType.ToString())
        {
            case "Changed":
                break;
            case "Deleted":
                break;
            case "Created":
                if (e.Name == "log.dat")
                {
                    parseDataFile();
                    moveHTMLtoLMS();

                }
                break;
            default:
                break;
        }
    }

有人知道为什么我需要休眠(或断点)才能使代码再次运行吗?

最佳答案

根据 System.IO.FileSystemWatcher 的文档类:

The Windows operating system notifies your component of file changes in a buffer created by the FileSystemWatcher. If there are many changes in a short time, the buffer can overflow. This causes the component to lose track of changes in the directory, and it will only provide blanket notification. Increasing the size of the buffer with the InternalBufferSize property is expensive, as it comes from non-paged memory that cannot be swapped out to disk, so keep the buffer as small yet large enough to not miss any file change events. To avoid a buffer overflow, use the NotifyFilter and IncludeSubdirectories properties so you can filter out unwanted change notifications.

可能是事件的消耗速度不够快,内部缓冲区不够大,无法处理所有通知。默认情况下,观察者处理 FileNameDirectoryNameLastWrite 通知,但您只使用创建事件(文件和目录)。您的应用程序是否快速连续运行?我会尝试在您的应用程序调用之间设置延迟(而不是事件处理程序),使用更具体的过滤器(只是 FileName 通知或使用 Filter< 仅监视日志文件 property),增加内部缓冲区大小或上述的任意组合。我认为这应该可以解决您的问题。

关于c# - FileSystemWatcher - 事件没有触发第二次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4541522/

相关文章:

.net - System.IO.FileSystemWatcher 监视网络服务器文件夹 - 性能注意事项

C# - 预测文件夹删除时的文件系统事件

c# - 避免在目录中一次更改太多错误

c# - Json 没有以所需的模式返回正确的值

c# - 为什么我的二进制文件可以在 Windows 8 上运行,但不能在 Windows 7 上运行?

C# 日期时间选择器 -> 使用 updown & pick

c# - SQL 'Time' C# 等效项 - System.TimeSpan 不起作用

c# - Linq Dynamic ParseLambda 未解析

c# - 如何跟踪文件和文件夹的复制/粘贴事件

c++ - 获取有关硬盘扇区原始数据更改的通知 - 文件更改通知