I want to use FileSystemWatcher to monitor a directory and its subdirectories for files that are moved. And then I want to trigger some code when all the files have been mov
Rx - throttle - makes this job easy. Here is a testable, reusable solution.
public class Files
{
public static FileSystemWatcher WatchForChanges(string path, string filter, Action triggeredAction)
{
var monitor = new FileSystemWatcher(path, filter);
//monitor.NotifyFilter = NotifyFilters.FileName;
monitor.Changed += (o, e) => triggeredAction.Invoke();
monitor.Created += (o, e) => triggeredAction.Invoke();
monitor.Renamed += (o, e) => triggeredAction.Invoke();
monitor.EnableRaisingEvents = true;
return monitor;
}
}
Lets merge events into a single sequence
public IObservable OnUpdate(string path, string pattern)
{
return Observable.Create(o =>
{
var watcher = Files.WatchForChanges(path, pattern, () => o.OnNext(new Unit()));
return watcher;
});
}
then finally, the usage
OnUpdate(path, "*.*").Throttle(Timespan.FromSeconds(10)).Subscribe(this, _ => DoWork())
u can obviously play with the throttle speed to suit your needs.