C# - Predict file system events on folder delete

前端 未结 3 529
礼貌的吻别
礼貌的吻别 2021-01-18 17:37

This is more a question about what\'s the best practice in implementing this.

I have a FileSystemWatcher which should inform me about User\'s changes on

3条回答
  •  执笔经年
    2021-01-18 18:09

    I've done exactly this sort of thing recently; the trick is to have your 'list' recognise that where there's a folder name in the list, also discard any events for anything within that folder if it's expecting a delete event, and only remove it from your prediction list if it's the folder itself.

    I should warn you though, you're likely to encounter problems with the FileSystemWatchers buffer becoming full if too many events happen in rapid succession; if this does, it'll fire an Error event, and fail to notify you of a whole bunch of events. If your prediction list removes items as it receives the event, you run the risk of ignoring future events just because the event you intended to ignore was never received due to a buffer overflow. It may also get very large, as items are never being removed from the list.

    I've yet to find a reliably way of doing this, although you can set the size of the FileSystemWatchers buffer to maximum to mitigate it to a degree.

    EDIT: Also very important: The events that come back do so on a different thread (unless your handler is on an object that implements ISynchronizeInvoke, such as a Control or Form, and you set the SynchronizingObject to your Control/Form. This means you need to be very careful how you maintain your list, taking into account potential race conditions. I'm still struggling with this one; my code flushes the prediction list on receiving an error event, but by the time it handles the event, other change events since the error have already been fired and handled, and it flushes things it shouldn't.

提交回复
热议问题