2

I'm making a backup system and dealing with the fact System.FileWatcher is raising multiple events per change (copying a file raises Created and Changed, for one) by queueing the commands.

Right now, I'm subscribing to events:

watcher.Changed += new FileSystemEventHandler(OnChanged);

and creating an object of a class:

    private void OnChanged(object sender, FileSystemEventArgs e)
    {
        var now = DateTime.Now;
        var change = new ChangeCommand(now, _fileLogPath, e.FullPath);
    }

ChangeCommand is a class that implements the ICommand interface. My question is how and when to actually enqueue them. Since trying to access a file that is being accessed would throw an exception, I want to keep Peek-ing until it doesn't and then Dequeue.

  • Possible duplicate of http://stackoverflow.com/questions/1406808/wait-for-file-to-be-freed-by-process – Tim Rutter Mar 31 '16 at 10:32
  • 1
    I don't think this would solve what sounds to be your main problem: There will never be a guarantee that you can access that file. There will always be several cpu ticks between a check that it is accessible and the real access, where in between some other process might have taken control of that file. – René Vogt Mar 31 '16 at 10:33
  • @RenéVogt This is true. OP perhaps should just keep trying to open the file until it succeeds - in a relatively slow loop. – Tim Rutter Mar 31 '16 at 10:40
  • There are better hammers for this job. The Volume Shadow Copy Service in Windows is built for dealing with files that are active. There's a .NET wrapper to use it that is available https://github.com/alphaleonis/AlphaVSS. – dbugger Mar 31 '16 at 11:50
  • @RenéVogt Obviously I'm going to try to access the file until it succeeds anyway. but a command queue makes sense here, no? After all, I might be registering hundreds of simultaneous changes. – Dmitrij Kramer Mar 31 '16 at 20:45

0 Answers0