繁体   English   中英

Windows 服务使用.net核心BackgroundService,如何优雅停止?

[英]Windows Service using .net core BackgroundService, how to gracefully stop?

我正在使用 .Net Core 3.1 开发 windows 服务

许多在线资源建议我为此使用BackgroundService 问题是我无法通过重写ExecuteAsync方法正常停止服务。

用于测试的代码设置非常简单:

public class MyService: BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        Console.WriteLine($"Service started at {DateTimeOffset.Now}");
        await DoLongRunningWork(stoppingToken);
    }

    public override async Task StopAsync(CancellationToken cancellationToken)
    {
        Console.WriteLine("Service is being stopped...");
        await base.StopAsync(cancellationToken);
        Console.WriteLine("Service stopped at {DateTimeOffset.Now}");
    }

    private static async Task DoLongRunningWork(CancellationToken token)
    {
        Console.WriteLine("I'm working...");
        while (!token.IsCancellationRequested)
        {
            Console.WriteLine($"\t... doing work ...");
            await Task.Delay(1000, token);
        }

        // THE BELOW LINE IS NEVER REACHED. i.e The line "Cancel requested? True" is never logged out...
        Console.WriteLine($"Cancel requested? {token.IsCancellationRequested}");
    }
}

Main方法


static void Main(string[] args)
{
    Console.WriteLine("Starting My Service...");
    Host.CreateDefaultBuilder(args)
        .UseWindowsService()
        .ConfigureServices(services =>
        {
            services.AddHostedService<MyService>();
        })
        .Build()
        .Run();
}

我可以做的一件事是实现我自己的Stop方法并在我的覆盖StopAsync中调用它。 但我很好奇为什么这个简单的设置没有按预期工作。

我已经阅读了BackgroundService.cs源代码,它看起来应该按我预期的方式工作(即这一行Cancel requested? True应该被注销,但它没有......

我试过将它作为控制台应用程序运行并使用Ctrl+C停止它,以及将它安装为 Windows 服务并使用service.msc来控制它。 相同的行为(即没有正常关机......)

非常感谢任何帮助!

我忘记了这么久。 当我回到它时,我发现了问题......这只是一个混乱

这条特别的线

await Task.Delay(1000, token);

将抛出TaskCancelledException因此循环将退出该方法将停止... @Jeremy Lakeman 确实对此发表了评论,但当时我没有想通我猜...

我只需要小心使用带有取消令牌的await Task.Delay(..., token) ...

所以,我创建了一个简单的扩展

    public static async Task SafeDelay(this Task source)
    {
        try
        {
            await source;
        }
        catch (TaskCanceledException)
        {
            // I don't want a throw on TaskCanceledException...
        }
    }
    private static async Task DoLongRunningWork(CancellationToken token)
    {
        Console.WriteLine("I'm working...");
        while (!token.IsCancellationRequested)
        {
            Console.WriteLine($"\t... doing work ...");
            
            // I simply want the loop to keep running, I don't want an absurd stop...
            await Task.Delay(1000, token).SafeDelay();
        }

        // This line is now reached...
        Console.WriteLine($"Cancel requested? {token.IsCancellationRequested}");
    }

在按照官方示例进行操作时,我遇到了同样的问题,捕捉到TaskCanceledException就成功了,这是我的代码现在的样子:

public class Worker : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Started");

        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                await Task.Delay(60000, stoppingToken);
            }
            catch (TaskCanceledException)
            {
                continue;
            }
        }

        _logger.LogInformation("Stopped");
    }
}

我现在收到“已停止”日志:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM