windows service startup timeout

2019-01-08 08:26发布

问题:

Is there a way to set a different value for service startup timeout per service? I can change it using the ServicesPipeTimeout registry key, but it's per machine (http://support.microsoft.com/kb/824344).

At the moment the only thing I thought about was to do all the time-consuming startup actions in a different thread.

回答1:

It's good practice to finish starting your service as fast as possible. So, during the start state, do only what you absolutely need to acknowledge it started successfully; and do the rest later. If the start is still a lengthy process, use SetServiceStatus periodically to inform the Service Control Manager that you have not yet finished, so it does not time-out your service.



回答2:

I agree with Romulo on finishing to start your service as soon as possible. However, if you need the time and you are using .NET Framework 2.0 or later, you might consider ServiceBase.RequestAdditionalTime() method.

http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.requestadditionaltime.aspx

protected override void OnStart()
{
    this.RequestAdditionalTime(10000);
    // do your stuff
}


回答3:

Simply do timeintensive stuff in another thread

   protected override void OnStart(string[] args)
    {
        var task = new Task(() =>
        {
            // Do stuff
        });
        base.OnStart(args);
        task.Start();
    }


回答4:

I also had to deal with a service which may takes a few seconds/minutes to have a good Start. When the service starts, it tries to connect to a SQL Server. However, when the whole server was restarted , my service was starting BEFORE SQL Server. (I know about the Service dependency but it dont apply to my situation for a particular reason....). I tried to do a loop trying 10 times to connect to SQL Server, but Windows was killing my service before the 2nd try, because of the Timeout.

My solution : I added a Timer in the "onStart()" of my service. Then, the "onTick()" method of the service was trying 10 times to connect to the SQL Server (with a waiting of 30 in it). No more Timeout at startup.

So basically,

  • My service starts in 5 seconds.
  • A timer is launched 10 seconds after the service is started.
  • The timer tries 10 times [waiting 30 seconds each time] to connect to the SQL Server.
  • If it succeed, the timer will disable itself, if not (after 10 try), I stop the service.

Note the more elegant way to resolve the problem but maybe some part of my solution may help anybody in the same situation than me,