FileSystemWatcher Changed event is raised twice

前端 未结 30 3311
死守一世寂寞
死守一世寂寞 2020-11-22 06:01

I have an application where I am looking for a text file and if there are any changes made to the file I am using the OnChanged eventhandler to handle the event

30条回答
  •  遥遥无期
    2020-11-22 06:31

    I think the best solution to solve the issue is to use reactive extensions When you transform event into observable, then you can just add Throttling(..) (originally called Debounce(..))

    Sample code here

            var templatesWatcher = new FileSystemWatcher(settingsSnapshot.Value.TemplatesDirectory)
            {
                NotifyFilter = NotifyFilters.LastWrite,
                IncludeSubdirectories = true
            };
    
            templatesWatcher.EnableRaisingEvents = true;
    
            Observable.FromEventPattern(
                    addHandler => templatesWatcher.Changed += addHandler,
                    removeHandler => templatesWatcher.Changed -= removeHandler)
                .Throttle(TimeSpan.FromSeconds(5))
                .Subscribe(args =>
                {
                    _logger.LogInformation($"Template file {args.EventArgs.Name} has changed");
                    //TODO do something
                });
    

提交回复
热议问题