tags:

views:

124

answers:

3

I need to ensure that all pending FileSystemWatcher events are processed before executing my operation. Is there any way to do this?

A: 

The FileSystemWatcher uses a buffer in non-paged memory to store the file system events. As you handle each event it is removed from this buffer, freeing space for new events.

It is not a queue or list that can grow indefinitely in size. If there are many events in a short time, the buffer is filled and then an Error event is thrown. So you don't have the ability to flush this buffer.

If you want to ensure the buffer is empty before you start handling events, the simplest approach would be to create a new FileSystemWatcher and start watching just before you need it. However you should be careful you don't create too many simultaneous watchers due to the reliance each has on storing the buffer in non-paged memory.

Ash
Well.. watcher generated first event, I've handled it... what next?
skevar7
Each time you handle an event, it is cleared from the buffer. That's why it is recommended to handle events as quickly as possible to help avoid filling the buffer.
Ash
I need to know if there are pending events in the buffer. How?
skevar7
You have no direct access to this buffer using the FileSystemWatcher. Your best bet is to add all events to a collection you create (ie a Dictionary or List), then when the collection contains enough events, process them. If you want more, FileSystemWatcher is not the right tool, look at Windows API.
Ash
I need to know if I've added _all_ pending events at the current moment. Is that possible without using WinAPI?
skevar7
A: 

If you're watching a file, open it for writing to lock it so that nobody else can access it and thus generate any new events. Then wait for a millisecond or so. Ugly? Yes.

CannibalSmith
No, I'm watching a folder's tree. Locking is not an option.
skevar7
A: 

My solution for this task.. So far it looks ok.

      while (true)
  {
   WaitForChangedResult res = watcher.WaitForChanged(WatcherChangeTypes.All, 1);
   if (res.TimedOut)
    break;
  }
skevar7