You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何阻止以Windows Service运行的.NET BackgroundService被停止?

如何在.NET Core BackgroundService中实现类似Topshelf的阻止服务停止功能?

更新说明

提出本问题并收到反馈后,我又提出了更贴合实际需求的问题,旨在吸引Topshelf领域的专家。由于本问题已有浏览量和回复,我未对其进行修改,避免彻底变更内容或添加过多信息导致问题冗长失焦。在此说明,我当时已找到一个适用的解决方案。

原始问题

  • 我按照微软的《使用BackgroundService创建Windows Service》教程创建了新的BackgroundService,试图从.NET Framework/Topshelf迁移。
  • Topshelf提供了一个bool Stop()方法,在服务停止前调用,返回false可阻止服务关闭。我需要此功能,但尝试用BackgroundService实现却未成功。
  • 我的服务包含通过监控文件夹中新增文件触发的长时间运行进程(可运行1小时以上)。当用户需要更新服务代码时,会停止服务、更新文件再重启。由于服务MMC管理单元中无进度显示,我希望在有进程运行时阻止关闭,同时设置了强制关闭逻辑:在Y秒滑动窗口内收到X次关闭请求时,允许服务关闭。
  • 我曾看到使用IHostApplicationLifetime并在CancellationToken ApplicationStopping上注册委托的方案,但我不想无限等待可能运行超1小时或出现严重问题的任务,而是希望用滑动窗口逻辑拒绝关闭请求。
  • BackgroundService.StopAsync无法提供帮助,因为它没有可设置的返回值或状态来阻止关闭,且当此重载执行时,IHostApplicationLifetime.StopApplication已被调用。
  • 我尝试继承WindowsServiceLifetime并传入自定义的ICancelableBackgroundService接口,但OnStop方法在工作流中触发时机过晚,无法阻止服务关闭。ServiceBase的设计似乎不支持拒绝关闭请求。以下是我编写的代码:
[System.Runtime.Versioning.SupportedOSPlatform( "windows" )]
public class CancelableWindowsServiceLifetime : WindowsServiceLifetime
{
    private readonly ICancelableBackgroundService cancelableBackgroundService;

    public CancelableWindowsServiceLifetime( IHostEnvironment environment, IHostApplicationLifetime applicationLifetime, ICancelableBackgroundService cancelableBackgroundService, ILoggerFactory loggerFactory, IOptions<HostOptions> optionsAccessor )
        : this( environment, applicationLifetime, cancelableBackgroundService, loggerFactory, optionsAccessor, Options.Create( new WindowsServiceLifetimeOptions() ) )
    {
    }

    public CancelableWindowsServiceLifetime( IHostEnvironment environment, IHostApplicationLifetime applicationLifetime, ICancelableBackgroundService cancelableBackgroundService, ILoggerFactory loggerFactory, IOptions<HostOptions> optionsAccessor, IOptions<WindowsServiceLifetimeOptions> windowsServiceOptionsAccessor )
        : base( environment, applicationLifetime, loggerFactory, optionsAccessor, windowsServiceOptionsAccessor )
    {
        this.cancelableBackgroundService = cancelableBackgroundService;
    }

    protected override void OnStop()
    {
        if ( !cancelableBackgroundService.CanStop() )
        {
            // 这里应该怎么做?抛出异常或直接返回都无法阻止服务关闭
            // throw new InvalidOperationException( "CancelableBackgroundService正在处理中,无法停止服务。" ); // 这仍然无法阻止服务关闭
            // return; // 这仍然无法阻止服务关闭。
        }

        base.OnStop();
    }
}

请问是否有可行的模式或机制来实现上述需求?


内容的提问来源于stack exchange,提问作者Terry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 21:22:22