.net - System.IO.FileSystemWatcher 的底层是如何工作的?

标签 .net windows file-io filesystemwatcher file-watcher

我想了解 System.IO.FileSystemWatcher 在幕后是如何工作的?因为我有一个要求,我需要查看 100 个或更多文件夹下的所有文件,其中每个文件夹将包含大约 1K 个文件。

我不确定我是否使用了 FileSystemwatcher 是否会创建许多线程来监视这些文件,从而影响我的应用程序的性能?那么您能否让我知道 System.IO.FileSystemWatcher 在幕后究竟是如何工作的,或者它是否在内部使用线程来监视这些目录?

最佳答案

在内部FileSystemWatcher使用Windows API ReadDirectoryChangesW函数(从 FileSystemWatcher reference source 可以看出)。 ReadDirectoryChangesW 的底层实现没有记录,但在回答您关于 FileSystemWatcher 是否创建单独的线程来监视文件的具体问题时,答案是“否”。

然而,值得强调 remarks 中的以下内容鉴于您的目录包含许多文件,请参阅文档中的 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.

从中可以得到两个结论:

  1. 对于许多 FileSystemWatcher 实例,将创建许多缓冲区来存储更改事件,并且这些缓冲区是从非分页内存分配的,这是一种有限的资源。
  2. 如果您正在监控的目录中发生大量更改,您可能会错过事件。

关于.net - System.IO.FileSystemWatcher 的底层是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71295028/

相关文章:

c# - 如何制作折线图从0 X轴开始

windows - 与Linux等效的Windows:查找-name

java - 为什么输入流找不到类文件夹之外的文件

file-io - 贝加莱有限公司。写入后计算新的偏移量或如何将数据写入新行

c# - 温莎城堡 : Will my transient component be garbage collected?

.net - 从 .NET 调用 COM,它是适配器模式的一个例子吗?

.net - 删除 VB.NET 源代码文件中的所有注释

php - PHP 中的文件组(使用 chgrp() 更改)是什么?

c++ - 如何在没有依赖的情况下构建 harfbuzz

Ruby 文件 IO 定界符?