How to run a task when a windows service starts?

The Light picture The Light · Apr 12, 2013 · Viewed 7.2k times · Source

I have a windows service and I've written the code to run the task within the OnStart() event:

 protected override void OnStart(string[] args)
        {
            this.DoTask();
        }

private void DoTask()
        {
            Task task1 = Task.Factory.StartNew(() => this.OriginalFileProcessor.StartPolling());

            try
            {
                Task.Wait(task1);
            }
            catch (Exception ex)
            {
                this.Log.Error("Failed running the task", ex);
            }           
        }

The DoTask is a never-ending loop. It will stop only when the service is stopped.

But when I try to start the service, it waits a long time then gives me the below error:

Windows could not start the ... service on Local Computer.
Error 1053: The service did not respond to the start or control request in a timely fashion.

How to resolve it?

Answer

Conrad Clark picture Conrad Clark · Apr 12, 2013

Why are you waiting your task to finish?

I think Task.Wait is blocking your current thread, then you're getting timeout while starting your service.

EDIT: You need to remove this block:

try
{
    Task.Wait(task1);
}
catch (Exception ex)
{
    this.Log.Error("Failed running the task", ex);
}  

Task.Wait is indeed blocking your current thread. According to MSDN:

Task.Wait Method

Waits for the Task to complete execution.

EDIT 2 Do this instead

Task task1 = Task.Factory.StartNew(() => this.OriginalFileProcessor.StartPolling()).ContinueWith( t =>
{
     var aggException = t.Exception.Flatten();
     foreach(var ex in aggException.InnerExceptions)
         this.Log.Error("Failed running the task", ex);
}, 
TaskContinuationOptions.OnlyOnFaulted);