.NET Core / .NET 5 中 BackgroundService 中 ServiceBase.OnCustomCommand 的等效项

问题描述

我使用 BackgroundService 工作器在 .NET Core(也在 .NET 5 中)创建了一个 Windows 服务,并使用 IHostBuilder.UseWindowsService() 调用将其作为 Windows 服务运行。

我的问题是,如何捕获 Windows 服务命令,例如

sc.exe control <my service name> 200

据我所知,在这种构建 Windows 服务的新方式中,我无法捕捉到与旧的 ServiceBase.OnCustomCommand 相同的东西。

任何有关如何捕获这些命令的帮助将不胜感激。即使答案只是“回到为您的 Windows 服务使用 ServiceBase”

谢谢!

解决方法

对于仍在寻找答案的任何人。请参阅 this answer on github 以获取解决方案

基本上是要注册一个自定义的 IHostLifetime 实现:

Host.CreateDefaultBuilder(args)
    .UseWindowsService()
    .ConfigureServices((hostContext,services) =>
    {
        if (WindowsServiceHelpers.IsWindowsService())
            services.AddSingleton<IHostLifetime,CustomService>();
    })

实际实现可能继承自 WindowsServiceLifetime,您可以在其中覆盖 OnCustomCommand 方法:

/// <summary>
/// Will handle custom service commands
/// </summary>
/// <param name="command">The command message sent to the service.</param>
protected override void OnCustomCommand(int command)
{
    _logger.LogInformation("Received custom service control command: {0}",command);
    switch (command)
    {
        case PreShutdownCommandCode:
            // Handle your custom command code
            break;
        default:
            base.OnCustomCommand(command);
            break;
    }
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...