Need to increase window service timeout

2019-06-19 00:24发布

问题:

i am facing problem during starting my window service... as there is a big load on OnStart() event of my service, it scrap data, saved it to database and send email. So my service need to increase start time because the defualt timeout is 30second... i have released that my service will need additional time to start when i face the following exception..

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

Plz help me... Thanx in advance

回答1:

i have realised that my service will need additional time to start when i face the following exception

doing long runnings tasks on constructor/start isn't good. you should start your long running task on a sperate thread.

Service startup should be instant and should not hang up.

However if you still want, you can do this

ServiceBase.RequestAdditionalTime(4000); // add 4 seconds

From MSDN

The RequestAdditionalTime method is intended to be called by the overridden OnContinue, OnPause, OnStart, or OnStop methods to request additional time for a pending operation, to prevent the Service Control Manager (SCM) from marking the service as not responding. If the pending operation is not a continue, pause, start, or stop, an InvalidOperationException is thrown.



回答2:

You better do your long operations in a Thread.

protected override void OnStart(string[] args)
{
  Thread thWorker = new Thread(new ThreadStart(
    delegate
    {
       // Do your long operations here
    }
  ));
  thWorker.Start();
}


回答3:

to debug the OnStart of service (it can be a "long running task"), i use this:

    Protected Overrides Sub OnStart(ByVal args() As String)
 #If CONFIG = "Debug" Then
        ' 2 minutes before timeout
        Me.RequestAdditionalTime(2 * 60 * 1000)
        Debugger.Launch()
 #End If
.
.
.
    End Sub


回答4:

As far as I know that hard limit is there exactly to prevent this sort of abusive behavior from services :)

Make your long running tasks run outside the startup of the service. Handle stopping the service gracefully, then you can automatically stop the service when it's done if you need to. There's no need to do everything on startup.



回答5:

Have you considered using task paraller library for this. This example is VB.Net but you get the idea:

Imports System.Threading.Tasks

Public Class Service1

    Private tasks As New List(Of Task)

    Protected Overrides Sub OnStart(ByVal args() As String)
        tasks.Add(Task.Factory.StartNew(Sub() DoWork()))
    End Sub

    Private Sub DoWork()
        ' Do long running work
    End Sub

    Protected Overrides Sub OnStop()
        Task.WaitAll(tasks.ToArray())
    End Sub

End Class