8

我一直在考虑将文件观察程序包装在可观察对象中以帮助处理事件,但我在弄清楚如何从中获得我想要的行为时遇到了一些麻烦。文件监视器监视放置文件的目录。当第一次将文件放入该目录时,文件观察程序会触发 Created 事件。但是,如果文件很大或网络连接缓慢,则在文件更新时会触发一系列 Changed 事件。我不想在文件完成写入之前处理文件,所以我真正需要的是这个时间线

|Created    |Changed   |Changed   |Changed                      
________________________________________________ 
^Write starts       ^Write finishes       ^Processing Starts    

我查看了许多在 Rx 中过滤事件的方法,但我无法得到我需要的“一旦文件文件在 X 秒内没有更改就触发函数”。油门不好,因为它会在中间丢失事件。缓冲区不好,因为事件可能发生在缓冲区边界上。

我曾考虑过使用超时,但我并不疯狂,他们抛出了异常,我希望处理在文件被写入时开始,而不是在没有更多事件时开始。

Reactive Extensions vs FileSystemWatcher有一个类似的问题,但从未真正解决。

有没有一种方法可以让我轻松做到这一点?我确信这不是一个不常见的用例。

4

4 回答 4

3

ObservableFileSystemWatcher- 围绕FileSystemWatcher类型的可观察包装器- 完美运行。添加一个命名为 NuGet 的包ReactiveFileSystemWatcher并创建一个控制台应用程序进行测试,如下所示

class Program
{
  static void Main(string[] args)
  {
    using (var watcher = new ObservableFileSystemWatcher(c => { c.Path = @"C:\FolderToWatch\"; c.IncludeSubdirectories = true; }))
    {
      watcher.Created.Select(x => $"{x.Name} was {x.ChangeType}").Subscribe(Console.WriteLine);
      watcher.Changed.Select(x => $"{x.Name} was {x.ChangeType}").Subscribe(Console.WriteLine);
      watcher.Renamed.Select(x => $"{x.OldName} was {x.ChangeType} to {x.Name}").Subscribe(Console.WriteLine);
      watcher.Deleted.Select(x => $"{x.Name} was {x.ChangeType}").Subscribe(Console.WriteLine);
      watcher.Errors.Subscribe(Console.WriteLine);
      watcher.Start();
      Console.ReadLine();
    }
  }
}
于 2016-04-17T15:09:12.597 回答
2

编辑:审查后,不认为你想要这个......

也许我有点过于简单化了,但在这里不是Throttle很理想吗?

这绝不是“简单”,但我认为它比我以前的想法更接近你想要的:

(奖励:有一个测试用例!;))

void Main()
{
    var pathToWatch = @"c:\temp\";
    var fsw = new FileSystemWatcher(pathToWatch);

    // set up observables for create and changed
    var changedObs = 
       Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(
          dlgt => fsw.Changed += dlgt, 
          dlgt => fsw.Changed -= dlgt);
    var createdObs = 
       Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>( 
          dlgt => fsw.Created += dlgt, 
          dlgt => fsw.Created -= dlgt);

    // the longest we'll wait between last file write and calling it "changed"
    var maximumTimeBetweenWrites = TimeSpan.FromSeconds(1);

    // A "pulse" ticking off every 10ms (adjust this as desired)
    var timer = Observable
        .Timer(TimeSpan.Zero, TimeSpan.FromMilliseconds(10))
        .Select(i => DateTime.Now);

    var watcher = 
        from creation in createdObs
        from change in changedObs
            // we only care about changes matching a create
            .Where(changeEvt => changeEvt.EventArgs.Name == creation.EventArgs.Name)
            // take latest of (pulse, changes) and select (event, time since last file write)
            .CombineLatest(timer, (evt, now) => new {
                    Change = evt, 
                    DeltaFromLast = now.Subtract(new FileInfo(evt.EventArgs.FullPath).LastWriteTime)})
            // skip all until we trigger than "time before considered changed" threshold
            .SkipWhile(evt => evt.DeltaFromLast < maximumTimeBetweenWrites)
            // Then lock on that until we change a diff file
            .Distinct(evt => evt.Change.EventArgs.FullPath)
        select change.Change;

    var disp = new CompositeDisposable();

    // to show creates
    disp.Add(
        createdObs.Subscribe(
           evt => Console.WriteLine("New file:{0}", 
                evt.EventArgs.FullPath)));

    // to show "final changes"
    disp.Add(
        watcher.Subscribe(
           evt => Console.WriteLine("{0}:{1}:{2}", 
                 evt.EventArgs.Name, 
                 evt.EventArgs.ChangeType, 
                 evt.EventArgs.FullPath)));

    fsw.EnableRaisingEvents = true;

    var rnd = new Random();
    Enumerable.Range(0,10)
        .AsParallel()
        .ForAll(i => 
            {
                var filename = Path.Combine(pathToWatch, "foo" + i + ".txt");
                if(File.Exists(filename))
                    File.Delete(filename);

                foreach(var j in Enumerable.Range(0, 20))
                {
                    var writer = File.AppendText(filename);
                    writer.WriteLine(j);
                    writer.Close();
                    Thread.Sleep(rnd.Next(500));
                }
            });

    Console.WriteLine("Press enter to quit...");
    Console.ReadLine();
    disp.Dispose();        
}
于 2013-01-04T19:41:53.807 回答
1

看看我在这个答案BufferWithInactivity中的扩展方法。

我认为您可以使用它来查找已更改事件中的不活动状态。

于 2013-01-05T23:25:50.343 回答
0

查看 NuGet 包Reactive FileSystemWatcher

源代码在GitHub 页面上

于 2014-11-01T22:33:35.980 回答