what is the maximum time windows service wait to process stop request and how to request for additional time
I wrote the following code to achieve it.
protected override void OnStop()
{
int timeout = 10000;
var task = Task.Factory.StartNew(() => MyTask());
while (!task.Wait(timeout))
{
RequestAdditionalTime(timeout);
}
}
The above code starts a Task in Parallel to the main thread (Task start running immediately), next line is to check if task is completed or not every 10 seconds and if it is not completed it requests additional 10 seconds and keep checking till task get completed.
Different settings for OS restart
Though a number of people have mentioned the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\WaitToKillServiceTimeout
registry key, according to this "Service Control Handler" article from Microsoft that registry entry only controls the max amount of time a service can take to shut down when Windows itself is being shut down or restarted:
<...> to prevent a service from stopping shutdown, there is a limit to how long the service controller waits. If the service is being shut down through the Services snap-in, the limit is 125 seconds. If the operating system is rebooting, the time limit is specified in the
WaitToKillServiceTimeout
value <...>
If Windows is not in the process of restarting or shutting down, then the default amount of time Windows will wait for a service to shut down is 30 seconds. However, applications can make requests for additional time, which will be honored up to 125 seconds total (summed across all requests).
On Windows Server 2003 and later, this default timeout can be changed via the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ServicesPipeTimeout
registry key, as described in this Microsoft support article (and this ServerFault question). It's not clear if this applies to Windows 7/8/10, as the article only mentions server versions.
If a restart/shutdown has been initiated on the machine, the WaitToKillServiceTimeout
registry key value (if present) specifies the maximum amount of time Windows will allow the application will be allowed, overriding the OS default.
Presumably this is so that applications cannot arbitrarily delay shutdown beyond the default (or what the administrator specified via the WaitToKillServiceTimeout
registry entry).
It's set in the registry on subkey:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control
with string value WaitToKillServiceTimeout
. If not defined, it defaults to 20000 (ms). On my machine it seems to be set to 12000 (12s). I have never touched it.