首页 > 解决方案 > 为什么我的 BackgroundService 立即停止?

问题描述

我正在使用 .NET Core 2.2,我想运行长时间运行的后台任务(如旧的 Windows 服务)。我想使用Microsoft.Extensions.Hosting.BackgroundService(在Microsoft.Extensions.Hosting.Abstractions汇编中)。

我的问题是我的服务立即启动和停止。我写了这个小样本来展示我所做的:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace MyHostedService
{
    internal static class Program
    {
        private static void Main()
        {
            new HostBuilder()
                .ConfigureServices((hostContext, services) => { services.AddHostedService<MyService>(); })
                .Build()
                .RunAsync();
        }
    }
    public class MyService : BackgroundService
    {
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            int count = 0;
            while (!stoppingToken.IsCancellationRequested)
            {
                Console.WriteLine($"Hit count: {++count}, IsCancellationRequested: {stoppingToken.IsCancellationRequested}");
                await Task.Delay(TimeSpan.FromSeconds(1));
            }
            Console.WriteLine($"IsCancellationRequested: {stoppingToken.IsCancellationRequested}");
            Console.WriteLine("The end.");
        }
    }
}

这是输出:

> Hit count: 1, IsCancellationRequested: False
Application started. Press Ctrl+C to shut down.
Hosting environment: Production
Content root path: C:\Users\(personnal path hidden)\MyHostedService\MyHostedService\bin\Debug\netcoreapp2.2\
> IsCancellationRequested: True
> The end.

C:\Program Files\dotnet\dotnet.exe (process 31088) exited with code 0.
To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
Press any key to close this window . . .

我保证,我没有按 Ctrl+C,也没有按 Escape 键。

我错过了什么吗?您能告诉我要更改哪些内容以确保服务将一直运行,直到我按 Ctrl+C 将其停止?

我希望得到如下所示的结果:

Application started. Press Ctrl+C to shut down.
Hosting environment: Production
Content root path: C:\Users\(personnal path hidden)\MyHostedService\MyHostedService\bin\Debug\netcoreapp2.2\
> Hit count: 1, IsCancellationRequested: False
> Hit count: 2, IsCancellationRequested: False
> Hit count: 3, IsCancellationRequested: False
> Hit count: 4, IsCancellationRequested: False
> Hit count: 5, IsCancellationRequested: False
> Hit count: 6, IsCancellationRequested: False
> Hit count: 7, IsCancellationRequested: False
> Hit count: 8, IsCancellationRequested: False
> Hit count: 9, IsCancellationRequested: False
> Hit count: 10, IsCancellationRequested: False
> Hit count: 11, IsCancellationRequested: False

...(现在我按 Ctrl+C)...

> IsCancellationRequested: True
> The end.

C:\Program Files\dotnet\dotnet.exe (process 31088) exited with code 0.
To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
Press any key to close this window . . .

标签: c#.net-core

解决方案


您以异步方式运行它,因此一旦您的主函数到达末尾,应用程序就会退出。这就是要求取消的地方。尝试等待服务:

private async Task Main()
{
    await new HostBuilder()
        .ConfigureServices((hostContext, services) => { services.AddHostedService<MyService>(); })
        .Build()
        .RunAsync();
}

推荐阅读