Windows 具有依赖关系的服务的关闭顺序

Order of shutdown of Windows services with dependencies

我有一个 C# 服务需要在 OS 重新启动后关闭之前将特定文本写入 SQL 服务器数据库。所以服务 MSSQL$SQLEXPRESS 不应该在我的服务之前停止,为了实现这一点,我使用命令

添加了 MSSQL$SQLEXPRESS 的依赖项
sc.exe config MyService depend= MSSQL$SQLEXPRESS

但是,它似乎不起作用,因为我仍然收到错误

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

OnShutdown() 中尝试写入数据库时​​。有时错误是“无效句柄”错误..

我错过了什么?此外,sc.exe qc MyService 显示依赖关系,但 services.msc 下的依赖关系不显示任何内容。为什么?

来自文档:

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