IHost.RunAsync() 永远不会返回

Mr.*_*. T 7 c# .net-core-3.0

我正在构建一个 .NET Core 3.1 应用程序,它将BackgroundService在 Docker 容器中运行。虽然我已经实现了 BackgroundService 的启动和关闭任务,并且该服务在通过 触发时肯定会关闭SIGTERM,但我发现该await host.RunAsync()调用永远不会完成 - 这意味着我的块中的剩余代码Main()不会执行。

我是否遗漏了某些内容,或者我不应该期望RunAsync()在后台服务完全停止后调用返回控制权?

(用我能想到的最简单的重现进行更新......)

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

    namespace BackgroundServiceTest
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                Console.WriteLine("Main: starting");
                try
                {
                    using var host = CreateHostBuilder(args).Build();

                    Console.WriteLine("Main: Waiting for RunAsync to complete");

                    await host.RunAsync();

                    Console.WriteLine("Main: RunAsync has completed");
                }
                finally
                {
                    Console.WriteLine("Main: stopping");
                }
            }

            public static IHostBuilder CreateHostBuilder(string[] args) =>
                Host.CreateDefaultBuilder(args)
                    .UseConsoleLifetime()
                    .ConfigureServices((hostContext, services) =>
                    {
                        services.AddHostedService<Worker>();

                        // give the service 120 seconds to shut down gracefully before whacking it forcefully
                        services.Configure<HostOptions>(options => options.ShutdownTimeout = TimeSpan.FromSeconds(120));
                    });

        }

        class Worker : BackgroundService
        {
            protected override async Task ExecuteAsync(CancellationToken stoppingToken)
            {
                Console.WriteLine("Worker: ExecuteAsync called...");
                try
                {
                    while (!stoppingToken.IsCancellationRequested)
                    {
                        await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
                        Console.WriteLine("Worker: ExecuteAsync is still running...");
                    }
                }
                catch (OperationCanceledException) // will get thrown if TaskDelay() gets cancelled by stoppingToken
                {
                    Console.WriteLine("Worker: OperationCanceledException caught...");
                }
                finally
                {
                    Console.WriteLine("Worker: ExecuteAsync is terminating...");
                }
            }

            public override Task StartAsync(CancellationToken cancellationToken)
            {
                Console.WriteLine("Worker: StartAsync called...");
                return base.StartAsync(cancellationToken);
            }

            public override async Task StopAsync(CancellationToken cancellationToken)
            {
                Console.WriteLine("Worker: StopAsync called...");
                await base.StopAsync(cancellationToken);
            }

            public override void Dispose()
            {
                Console.WriteLine("Worker: Dispose called...");
                base.Dispose();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Dockerfile:

    #See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.

    FROM mcr.microsoft.com/dotnet/core/runtime:3.1-buster-slim AS base
    WORKDIR /app

    FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build
    WORKDIR /src
    COPY ["BackgroundServiceTest.csproj", "./"]
    RUN dotnet restore "BackgroundServiceTest.csproj"
    COPY . .
    WORKDIR "/src/"
    RUN dotnet build "BackgroundServiceTest.csproj" -c Release -o /app/build

    FROM build AS publish
    RUN dotnet publish "BackgroundServiceTest.csproj" -c Release -o /app/publish

    FROM base AS final
    WORKDIR /app
    COPY --from=publish /app/publish .
    ENTRYPOINT ["dotnet", "BackgroundServiceTest.dll"]
Run Code Online (Sandbox Code Playgroud)

docker-compose.yml:

    version: '3.4'

    services:
      backgroundservicetest:
        image: ${DOCKER_REGISTRY-}backgroundservicetest
        build:
          context: .
          dockerfile: Dockerfile
Run Code Online (Sandbox Code Playgroud)

通过运行此命令docker-compose up --build,然后在第二个窗口中运行docker stop -t 90 backgroundservicetest_backgroundservicetest_1

控制台输出显示工作线程关闭并被处理,但应用程序(显然)在RunAsync()返回之前终止。

    Successfully built 3aa605d4798f
    Successfully tagged backgroundservicetest:latest
    Recreating backgroundservicetest_backgroundservicetest_1 ... done
    Attaching to backgroundservicetest_backgroundservicetest_1
    backgroundservicetest_1  | Main: starting
    backgroundservicetest_1  | Main: Waiting for RunAsync to complete
    backgroundservicetest_1  | Worker: StartAsync called...
    backgroundservicetest_1  | Worker: ExecuteAsync called...
    backgroundservicetest_1  | info: Microsoft.Hosting.Lifetime[0]
    backgroundservicetest_1  |       Application started. Press Ctrl+C to shut down.
    backgroundservicetest_1  | info: Microsoft.Hosting.Lifetime[0]
    backgroundservicetest_1  |       Hosting environment: Production
    backgroundservicetest_1  | info: Microsoft.Hosting.Lifetime[0]
    backgroundservicetest_1  |       Content root path: /app
    backgroundservicetest_1  | Worker: ExecuteAsync is still running...
    backgroundservicetest_1  | Worker: ExecuteAsync is still running...
    backgroundservicetest_1  | info: Microsoft.Hosting.Lifetime[0]
    backgroundservicetest_1  |       Application is shutting down...
    backgroundservicetest_1  | Worker: StopAsync called...
    backgroundservicetest_1  | Worker: OperationCanceledException caught...
    backgroundservicetest_1  | Worker: ExecuteAsync is terminating...
    backgroundservicetest_1  | Worker: Dispose called...
    backgroundservicetest_backgroundservicetest_1 exited with code 0
Run Code Online (Sandbox Code Playgroud)

Mr.*_*. T 8

在 Github 上进行了长时间的讨论后,发现一些小的重构就解决了这个问题。简而言之,.RunAsync()阻塞直到主机完成并处置主机实例,这(显然)终止应用程序。

通过将代码更改为 call .StartAsync()and then ,控制确实会按预期await host.WaitForShutdownAsync()返回。Main()最后一步是将主机放置在finally块中,如下所示:

static async Task Main(string[] args)
{
    Console.WriteLine("Main: starting");
    IHost host = null;
    try
    {
        host = CreateHostBuilder(args).Build();

        Console.WriteLine("Main: Waiting for RunAsync to complete");
        await host.StartAsync();

        await host.WaitForShutdownAsync();

        Console.WriteLine("Main: RunAsync has completed");
    }
    finally
    {
        Console.WriteLine("Main: stopping");

        if (host is IAsyncDisposable d) await d.DisposeAsync();
    }
}
Run Code Online (Sandbox Code Playgroud)