FileSystemwatcher for a list of files

瘦欲@ 提交于 2019-12-02 00:58:07

The key point here is what does "together" mean to you. after all the system does an independent delete operation for each, which would technically mean they are not all deleted at the exact same time, but if you just wanna be close, let's say if they are all deleted within 5 seconds of each other then we only want OnChange to fire once, you can do the following. Note that this doesn't handle the rename change notification. You weren't listening for it, so I assumed you don't need to.

you may wanna change the 5 seconds window to a small window depending on your use.

    class SlowFileSystemWatcher : FileSystemWatcher
    {
        public delegate void SlowFileSystemWatcherEventHandler(object sender, FileSystemEventArgs args);

        public event SlowFileSystemWatcherEventHandler SlowChanged;
        public DateTime LastFired { get; private set; }

        public SlowFileSystemWatcher(string path)
            : base(path)
        {
            Changed += HandleChange;
            Created += HandleChange;
            Deleted += HandleChange;
            LastFired = DateTime.MinValue;
        }

        private void SlowGeneralChange(object sender, FileSystemEventArgs args)
        {
            if (LastFired.Add(TimeSpan.FromSeconds(5)) < DateTime.UtcNow)
            {
                SlowChanged.Invoke(sender, args);
                LastFired = DateTime.UtcNow;
            }
        }

        private void HandleChange(object sender, FileSystemEventArgs args)
        {
            SlowGeneralChange(sender, args);
        }

        protected override void Dispose(bool disposing)
        {
            SlowChanged = null;
            base.Dispose(disposing);
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!