How to start a task when starting a Windows service?

I have a Windows service and I wrote code to run the task in 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); } } 

DoTask - an infinite loop. It only stops when the service stops.

But when I try to start the service, it waits a long time and then gives me the following 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 solve it?

+6
source share
3 answers

Why are you waiting for the completion of your task?

I think Task.Wait blocks your current thread, then you get a timeout when the service starts.

EDIT: you need to remove this block:

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

Task.Wait really blocks your current thread. According to MSDN :

Task.Wait Method

Waits for a task to complete.

EDIT 2 Do it 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); 
+7
source

I guess this is because you are waiting for OriginalFileProcessor.StartPolling() , but this will never happen. You must transfer your instance of the task to a separate element and not wait for its completion:

 private Task m_task = null; private void DoTask() { try { m_task = Task.Factory.StartNew(() => this.StartPolling()); } catch { this.Log.Error("Unable to start task", ex); throw; // Rethrow, so that the OS knows, there was something wrong. } } private void StartPolling() { try { this.OriginalFileProcessor.StartPolling(); } catch (Exception ex) { this.Log.Error("Failed running the task", ex); } } 
+2
source

In the loop, you need to check whether the β€œstop status” is stopped and exit the loop. You have 5 seconds to do this before the OS decides to kill you.

+1
source

All Articles