C# - Predict file system events on folder delete

前端 未结 3 564
礼貌的吻别
礼貌的吻别 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:24

    Regarding the buffer overflow. The best way to solve it is to do the work in response to an event on another thread. I do it like this

    // Queue of changed paths.
    private readonly Queue mEventQueue = new Queue();
    
    // add this as handler for filesystemwatcher events
    public void FileSystemEvent(object source, FileSystemEventArgs e) {
        lock (mEventQueue) {
            if (!mEventQueue.Contains(e.FullPath)) {
                mEventQueue.Enqueue(e.FullPath);
                Monitor.Pulse(mEventQueue);
            }
        }
    }
    
    // start this on another thread
    public void WatchLoop() {
        string path;
        while (true) {
            lock (mEventQueue) {
                while (mEventQueue.Count == 0)
                    Monitor.Wait(mEventQueue);
                path = mEventQueue.Dequeue();
                if (path == null)
                   break;
            }
            // do whatever you want to do
         }
    }
    

    That way I will never miss an event

提交回复
热议问题