I have a doubt using FileSystemWatcher in C#.
I need to be notified when a file is created in a specified folder, but the problem is if I create multiple files at the same time multiple events are beeing fi开发者_运维技巧red and I need that the code only continues if the previous file was processed and not process multiple files at the same time.Any clue how to do that?
Many thanks
pseudo-code:
bool wasLastObjectProcessed = true
function onFileWatcherCreateFile
lock wasLastObjectProcessed
if wasLastObjectProcessed and processFile(file)
#do some code here that you need to do if it is processed
else
wasLastObjectProcessed = false
endif
endlock
endfunction
- Create a
Queue<T>
- Enqueue in the
FileSystemWatcher
- Dequeue in another thread
Make sure you use it in a thread safe manner using Queue.Synchronized
The way I handle filesystemwatchers is that whenever an event fires I add details of that event to a queue. I then set a timer for 5 seconds time to the process the queue. This timer will hopefully ensure that files have finished copying and that all operations are complete (ie multiple events being raised).
When processing the queue you can use a lock to make sure the queue is only processed by one thread at any given time and then you can just take stuff off the queue and process it until the queue is empty and then you're done.
If you want to be able to add to the queue while its processing you might need to do some appropriate locking.
精彩评论