Watcher.Created += (_, e) => queue.Add(e.FullPath) Watcher.Changed += (_, e) => queue.Add(e.FullPath) ProcessedFileMap = new ConcurrentDictionary() Watcher = new FileSystemWatcher( filter: "*.txt") Private ConcurrentDictionary processedFileMap At this point, it makes sense to encapsulate all of this behavior (FileSystemWatcher initialization, queue processing loop, and the duplicate event detection logic) in a class. When you see a file again and its modified date hasn’t changed, it means this is a duplicate event that can be ignored. To solve this problem, you can keep track of files you’ve processed and their modified dates with a concurrent dictionary. This is a problem because it can lead to processing the file multiple times when you really only want to process it once. 3 – Prevent processing the same file change multiple timesįileSystemWatcher fires multiple events when a file is created or modified (as shown in step 1 and step 2 above). This results in the file path getting enqueued and processed three times. Content=hello world Code language: plaintext ( plaintext )Īs mentioned in step 1, Created/Changed fire multiple times. This makes the event handlers exit as quickly as possible, which minimizes how much buffer space is being used. In the Changed/Created event handlers, add the file change info (such as the file path) to the queue. I recommend using a concurrent queue – such as a BlockingCollection (blocking queue) or a Channel (async queue). Process the file changes with a concurrent queue.This has a default of 8 KB and a max of 64 KB. Increase the buffer size with the InternalBufferSize property.There’s two things you can do to solve this problem: This results in you missing file changes. 2 – Process file change events with a concurrent queueįileSystemWatcher stops sending file change events when its internal buffer is full. In step 3, I’ll show how you can prevent processing the same file change repeatedly. For example, when a file is moved from one directory to another, several OnChanged and some OnCreated and OnDeleted events might be raised Microsoft – FileSystemWatcher API documentation This is known, intentional behavior:Ĭommon file system operations might raise more than one event. File changed: C:\temp\movies.txt Code language: plaintext ( plaintext )
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |