Search code examples
c#sql-serverwindowsservicesystem-shutdown

Order of shutdown of Windows services with dependencies


I have a C# service that requires to write a certain text to a SQL Server database before shutting down after OS restart. So the service MSSQL$SQLEXPRESS should not stop before my service and in order to achieve this, I have added a dependency of MSSQL$SQLEXPRESS using the command

sc.exe config MyService depend= MSSQL$SQLEXPRESS

However, it does not seem to work as I am still getting error

SHUTDOWN is in progress.
Login failed for user 'user'.
Cannot continue the execution because the session is in the kill state

when trying to write to the database in OnShutdown(). Sometimes the error is an "invalid handle" error..

What am I missing? Also, sc.exe qc MyService shows the dependency, but dependencies under services.msc shows nothing. Why?


Solution

  • From the docs:

    Note that during service shutdown, by default, the SCM does not take dependencies into consideration. The SCM enumerates the list of running services and sends the SERVICE_CONTROL_SHUTDOWN command. Therefore, a service may fail because another service it depends on has already stopped.

    To set the shutdown order of services manually, create a multistring registry value that contains the service names in the order in which they should be shut down and assign it to the Control key's PreshutdownOrder value, as follows:

    HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\PreshutdownOrder="Shutdown Order"

    Service Control Handler Function