禁用 FileSystemWatcher 以获取特定更新?
有谁知道当我的应用程序对目录中的文件进行更改时如何可靠地禁用 FileSystemWatcher 对象,以便我只监视对目录的外部更改?
我尝试在执行写入之前立即将 EnableRaisingEvents
设置为 false,并在执行写入后立即将其设置回 true,但似乎此方法不可靠,有时我仍然会触发事件。
我唯一能想到的另一件事是在执行写入后等待一小段时间,让操作系统完成目录的修改,然后再重新启用 FSW,但这看起来很黑客,我不喜欢它。
更糟糕的是,该目录可能包含许多文件,这些文件的身份超出了我的知识和控制范围,因此我不能只是等待特定文件的事件触发然后忽略它。一次修改后可能会触发任意数量的 FSW 事件(因为可能会更新许多文件)。
Does anyone have any ideas how I can reliably disable a FileSystemWatcher object when my application makes changes to the files in the directory, so that I am only watching for external changes to the directory?
I've tried setting EnableRaisingEvents
to false immediately before performing a write and setting it back to true immediately after, but it seems this method is not reliable, and occasionally I still get the event firing.
The only other thing I can think of is to wait a small amount of time after performing the write to let the OS finish up the modification of the directory before re-enabling the FSW, but that seems hackish and I don't like it.
To add to the problem, the directory consists of potentially many files, the identities of which are beyond my knowledge and control, so I can't just wait for the event to fire for a specific file and then ignore it. There could be any number of FSW events firing after a single modification (because of the potentially many files getting updated).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法使用 .NET API 执行此操作。
正如多个用户指出的那样,您可能最好维护所做更改的列表,并从您观察到的更改集中减去它们。
您还可以使用 Win32 级 API,如果我没有记错的话,它会为您提供进行更改的进程的 PID(对此不确定,我之前编写过一个驱动程序,它在内核空间内执行了此操作(以及更多操作) )。
更新:我给与我一起参与这个项目的团队中的某个人打电话,他们确认我们仅在内核空间中拥有 PID。
You cannot do this using the .NET API.
As multiple users pointed out, you'll probably be better off maintaining a list of changes you make and subtract them from the changeset you observe.
You can also use Win32-level API, which gives you a PID for the process making the change if I'm not mistaken (not sure about this, I've written a driver before which did this (and more) inside the kernel space).
UPDATE: I called someone on the team I worked with on this project, and they confirm we had the PID in kernel space only.