I need to create a method for listening to events and waiting for a certain amount of silence before calling another function.
Specifically, I am listening to a directory for file updates. When a file change occurs, my “directoryUpdate” function is called. From there I add the file to a list and create a thread called “timerThread” which sleeps for 2 seconds. When that thread is done sleeping, it calls a “gatherFinished” function.
But since directoryUpdate gets called 10 times all at once if 10 files change, it would launch 10 threads which seems like a bad way of doing this.
In the end I want a list of the file changes that occurred within 2 seconds of each other. I figure if there is a way to reset the sleep time to 2 seconds every time a change occurs and wait for the 2 seconds to finish, then I will have what I need. But there is no way to reset the timer as far as I know.
What is the best way of doing this?
UPDATE
Thanks for all your great answers. I am sorry for putting emphasis on getting the list of files. The event (file change) should not matter. I meant to focus on making sure the call to “gatherFinished” happens once at the right time – 2 seconds after all events in question have stopped firing. My question is on the nature of waiting, not on the nature of files or collections.
You could just use an AutoResetEvent and wait 2 seconds on it. If the event is triggered then you loop and wait another 2 seconds.
NOTE: I didn’t put any code to specify you how to synchronize the thread that will receive the directory changes and the timer thread. You will have to do that youself.