首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在ServiceBase.OnCustomCommand核/ .NET 5中BackgroundService中等效的.NET

在ServiceBase.OnCustomCommand核/ .NET 5中BackgroundService中等效的.NET
EN

Stack Overflow用户
提问于 2021-01-05 20:08:51
回答 1查看 977关注 0票数 2

我使用一个.NET工作人员在Windows中创建了一个Windows (也在.NET 5中),使用IHostBuilder.UseWindowsService()调用作为Windows运行它。

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

sc.exe control <my service name> 200

据我所知,我无法用这种构建Windows的新方法捕获到与旧的ServiceBase.OnCustomCommand相同的内容。

任何关于如何捕获这些命令的帮助都将不胜感激。即使答案是“回到Windows中使用ServiceBase”。

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-15 10:58:39

对于那些还在寻找答案的人来说。有关解决方案,请参见关于github的答案

它基本上即将注册一个自定义IHostLifetime实现:

代码语言:javascript
复制
Host.CreateDefaultBuilder(args)
    .UseWindowsService()
    .ConfigureServices((hostContext, services) =>
    {
        if (WindowsServiceHelpers.IsWindowsService())
            services.AddSingleton<IHostLifetime, CustomService>();
    })

实际的实现可能是从WindowsServiceLifetime继承的,在这里您可以重写OnCustomCommand方法:

代码语言:javascript
复制
/// <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;
    }
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65585865

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档