我想了解 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.
从中可以得到两个结论:
- 对于许多
FileSystemWatcher
实例,将创建许多缓冲区来存储更改事件,并且这些缓冲区是从非分页内存分配的,这是一种有限的资源。 - 如果您正在监控的目录中发生大量更改,您可能会错过事件。
关于.net - System.IO.FileSystemWatcher 的底层是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71295028/