Thursday, 3 October 2013

Background task - how to stop in a controlled manner?

Background task - how to stop in a controlled manner?

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:-
new TaskFactory().StartNew(_indexingService.StartService);
The StartService() method looks something like this:-
private readonly ManualResetEvent _resetEvent = new ManualResetEvent(false);
public void StartService()
{
var watcher = new FileSystemWatcher
{
// Set the properties
};
watcher.Changed += UpdateIndexes();
_resetEvent.WaitOne();
}
When the application is closing, I intend to call this method, which I
understand will end the indexing service background task:-
public void StopService()
{
_resetEvent.Set();
}
First of all, is this the right "pattern" for starting and stopping a
background task that should run for the lifetime of an application?
Second, how "graceful" would this shutdown be? Let's say that the watcher
Changed 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?