Home >Backend Development >C++ >Why Does My FileSystemWatcher Trigger the Changed Event Twice?
The ChangEd event of FilesystemWatcher Repeat the problem with repeated triggers
Problem description:
When monitoring text file changes using the FileSystemWatcher class, each time it is modified and saved the file, the OnChanged event will trigger twice.
Code example:
Analysis of the cause:
<code class="language-csharp">public void Initialize() { FileSystemWatcher fileWatcher = new FileSystemWatcher(); fileWatcher.Path = "C:\Folder"; fileWatcher.NotifyFilter = NotifyFilters.LastWrite; fileWatcher.Filter = "Version.txt"; fileWatcher.Changed += new FileSystemEventHandler(OnChanged); fileWatcher.EnableRaisingEvents = true; } private void OnChanged(object source, FileSystemEventArgs e) { // ...事件处理逻辑... }</code>This is a limitation known to the FileSystemWatcher class. When the application (such as notepad) performs the file system in batches, even if only one file is modified, this class will trigger multiple file system events.
Solution:
Although attributes can sometimes alleviate this problem, in some cases, they may need to be manually filter and repeat incidents.
Optimize the suggestion used by FileSystemWatcher:
Filter repeat events based on other conditions (such as file size or content). NotifyFilter
Considering a third -party library that provides improved FileSystemWatcher functions.
The above is the detailed content of Why Does My FileSystemWatcher Trigger the Changed Event Twice?. For more information, please follow other related articles on the PHP Chinese website!