3

My scenario:

  • Windows Service .NET 4
  • I poll a database for entities.
  • When new entities come in they are added to a BlockingCollection.
  • In the service's OnStart I create a System.Threading.Tasks.Task whose job is to enumerate the BlockingCollection (using GetConsumingEnumerable()).

The problem I'm having is this:

  • When an unhandled exception occurs in the task, I want the exception logged and the service stopped.
  • I can't catch exceptions from the task unless I call Task.Wait().
  • If I call Task.Wait() the OnStart method blocks and the service never finishes starting.

So how can I make this work?

Adi Lester
  • 24,731
  • 12
  • 95
  • 110
Ronnie Overby
  • 45,287
  • 73
  • 267
  • 346

1 Answers1

4

You can handle exceptions in a task using the `.ContinueWith' method:

Task.Factory.StartNew(() => {

    // Do some long action
    Thread.SpinWait(5000000);

    // that eventually has an error :-(
    throw new Exception("Something really bad happened in the task.");

    // I'm not sure how much `TaskCreationOptions.LongRunning` helps, but it sounds 
    // like it makes sense to use it in your situation.
}, TaskCreationOptions.LongRunning).ContinueWith(task => {

    var exception = task.Exception;

    /* Log the exception */

}, TaskContinuationOptions.OnlyOnFaulted); // Only run the continuation if there was an error in the original task.
Justin Rusbatch
  • 3,992
  • 2
  • 25
  • 43
  • 1
    Note for newbies trying the above code sample in a prototype application: Create the task using a variable- ` Task myTask = ; myTask.Wait();` The myTask.Wait() would cause the main thread to wait on the task created so that you may see the above in action – Sudhanshu Mishra Apr 01 '12 at 17:50