title: How to synchronize handling of filesystemwatcher events?
body: <p>I have the following synchronization problem.</p>
  
  <p>A thread runs in a loop and if it detects a folder in filesystem which was not processed yet (it may have been added while the app was not running), the folder is processed as a new folder by <code>Process</code> method: </p>
  
  <pre><code>void Loop()
  {
   while (run)
   {
    lock(renameLock)
    {
      var newFolders = EnumerateNewFolders().ExceptThoseMarkedAsRenamed();
      Process(newFolders);
      MarkAsProcessed(newFolders);
    }
    Sleep();
   }
  }
  </code></pre>
  
  <p>Renamed folders should not be processed as new but rather processed as renamed and marked as renamed so that they are not processed as new later.</p>
  
  <p>To take care of this, I have a <code>FileSystemWatcher</code> and a handler for the <code>Renamed</code> event:</p>
  
  <pre><code>private void fsw_Renamed(object sender, RenamedEventArgs e)
  {
    lock(renameLock)
    {
      ProcessRename(e);
      //mark folder as renamed so that ExceptThoseMarkedAsRenamed filters it out
      MarkAsRenamed(e);
    }
  }
  </code></pre>
  
  <p>Usually this works and when a rename is performed, the folder is first marked as renamed in <code>fsw_Renamed</code> and then filtered out in the loop by <code>ExceptThoseMarkedAsRenamed</code> and not processed as new.</p>
  
  <p>But sometimes the following order occurs:</p>
  
  <ol>
  <li>Folder is renamed in Windows Explorer and in the filesystem (while the Loop is holding lock)</li>
  <li>fsw_Renamed occurs, but cannot obtain the lock</li>
  <li>The looping thread is still holding lock and picks up the folder as new (it was not marked as renamed yet)</li>
  <li>The looping thread releases the lock</li>
  <li>Renamed event occurs, gets the lock, and folder is marked as renamed. But it is already too late since it was already processed as new.</li>
  </ol>
  
  <p>I am having trouble figuring out how to ensure that a renamed folder is never processed as new. </p>
  
  <p>A renamed folder is such folder for which the <code>Renamed</code> event <strong>occurred or will occur in near future</strong>, because there is an inherent delay between filesystem change and the <code>FileSystemWatcher.Renamed</code> event (and the actual change in filesystem and the event raised are not atomic).</p>
  
  <p><strong>How to ensure that the change done by fsw_Renamed is always taken into account by the Loop, even if the event occurred while Loop was holding the lock?</strong></p>