title: Background task - how to stop in a controlled manner?
body: <p>I'm developing a WPF application that will have an "indexing service" running as a background task. The indexing service will utilise a FileSystemWatcher that monitors a folder - when a file changes the indexing service will read in the file contents and update an index (I'm using Lucene.Net). My indexing service is a singleton, and will be started during application startup like this:-</p>
  
  <pre><code>new TaskFactory().StartNew(_indexingService.StartService);
  </code></pre>
  
  <p>The <code>StartService()</code> method looks something like this:-</p>
  
  <pre><code>private readonly ManualResetEvent _resetEvent = new ManualResetEvent(false);
  
  public void StartService()
  {
      var watcher = new FileSystemWatcher
      {
          // Set the properties
      };
      watcher.Changed += UpdateIndexes();
  
      _resetEvent.WaitOne();
  }
  </code></pre>
  
  <p>When the application is closing, I intend to call this method, which I understand will end the indexing service background task:-</p>
  
  <pre><code>public void StopService()
  {
      _resetEvent.Set();
  }
  </code></pre>
  
  <p>First of all, is this the right "pattern" for starting and stopping a background task that should run for the lifetime of an application? </p>
  
  <p>Second, how "graceful" would this shutdown be? Let's say that the watcher <code>Changed</code> event handler has fired and is iterating through the files, reading them and updating the indexes. If the task was stopped, will this processing be aborted mid-flow, or will the event handler method run to completion first?</p>