Skip to content

IHost.RunAsync() never completes #44086

Closed

Description

@martyt

Describe the bug

I'm building a .NET Core 3.1 app that will run a BackgroundService in a Docker container. While I've implemented the startup and shutdown tasks for the BackgroundService and the service is definitely shutting down when triggered via SIGTERM, I'm finding that the await host.RunAsync() call never completes - meaning the remaining code in my Main() block isn't executed.

To Reproduce

Use latest Microsoft.Extensions.Hosting package

Program.cs:

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();
        }
    }
}

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"]

docker-compose.yml:

version: '3.4'

services:
  backgroundservicetest:
    image: ${DOCKER_REGISTRY-}backgroundservicetest
    build:
      context: .
      dockerfile: Dockerfile

Start the app with docker-compose up --build and see the console logging from the application indicating that the service is running.

Run a second command prompt window and execute docker stop -t 90 backgroundservicetest_backgroundservicetest_1 and see that the app shuts down gracefully but never writes any of the console messages after the call to await host.RunAsync()

Expected behavior

After the BackgroundService completes shutting down, control should be returned to the method that called .RunAsync()

Screenshots

Console output from docker-compose

    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

Activity

  1. BrennanConroy commented on Oct 21, 2020

    @BrennanConroy
    Member

    Do you see the same issue outside of a docker container? I believe we've heard of issues before with docker-compose not flushing output correctly on process exit.

  2. martyt commented on Oct 21, 2020

    @martyt
    Author

    @BrennanConroy Thanks for the reply. Running as a Windows console app, I do see the host.RunAsync() call completing and the remainder of my code executing.

    I'm not sure this is just an issue with output flushing -- the code after host.RunAsync() simply never executes when running in a container. I can set a breakpoint at any location after the .RunAsync() call when running docker-compose in the VS debugger, and the breakpoint never gets hit.

  3. BrennanConroy commented on Oct 23, 2020

    @BrennanConroy
    Member

    You can deconstruct the Host.RunAsync method and put your console writes before DisposeAsync() if you want them to show up before docker exits.

    public static async Task RunAsync(this IHost host, CancellationToken token = default)
    {
    try
    {
    await host.StartAsync(token).ConfigureAwait(false);
    await host.WaitForShutdownAsync(token).ConfigureAwait(false);
    }
    finally
    {
    if (host is IAsyncDisposable asyncDisposable)
    {
    await asyncDisposable.DisposeAsync().ConfigureAwait(false);
    }
    else
    {
    host.Dispose();
    }
    }
    }

  4. BrennanConroy commented on Oct 23, 2020

    @BrennanConroy
    Member

    @maryamariyan Is changing the way hosting shuts down, so users can run code after RunAsync if they want, something Runtime would be interested in doing?

  5. Dotnet-GitSync-Bot commented on Oct 30, 2020

    @Dotnet-GitSync-Bot
    Collaborator

    I couldn't figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label.

  6. added
    untriaged
    on Oct 30, 2020
  7. pinkfloydx33 commented on Oct 31, 2020

    @pinkfloydx33

    I know this sound silly, but have you tried using a using block instead? I seem to recall a similar issue that I had which was resolved that way.

    var host = CreateHostBuilder(args).Build();
    using(host) {
       await host.RunAsync();
    } 
    Console.WriteLine("...");
  8. removed
    untriaged
    on Mar 1, 2021
  9. added this to the 6.0.0 milestone on Mar 1, 2021
  10. 9 remaining items

  11. maryamariyan commented on Mar 31, 2021

    @maryamariyan
    Contributor

    I see. I think there is no support for using SIGTERM for shutting down due to the explanation in #44086 (comment)

  12. davidfowl commented on Mar 31, 2021

    @davidfowl
    Member

    We support SIGTERM out of the box (hooking process exit).

  13. maryamariyan commented on Mar 31, 2021

    @maryamariyan
    Contributor

    @martyt do you mind please testing this on 5.0? @ericstj mentioned there was a runtime fix made for this on the last release.

  14. ericstj commented on Mar 31, 2021

    @ericstj
    Member

    Right, this looks like a duplicate of #36089 to me. That was fixing ProcessExit on docker on Windows.

  15. martyt commented on Mar 31, 2021

    @martyt
    Author

    @maryamariyan I updated the project to .NET 5.0 and tried both 5.0-buster-slim and 5.0-focal (sdk and runtime) and observed no difference in behavior. None of the code after the call to .RunAsync() gets executed when I stop the container via docker stop -t 90 backgroundservicetest_backgroundservicetest_1

    For reference I'm running the most recent release of Docker Desktop.

  16. martyt commented on Mar 31, 2021

    @martyt
    Author

    @martyt if the docker container is shutting down anyway, why you care having the AsuncRun to exit? I don't think you need to depend on that.

    @tarekgh - If .RunAsync() never returns, it's difficult to do any required cleanup prior to application exit. Doesn't matter what I need to run - the bottom line is, I have code after .RunAsync() that isn't getting executed.

  17. davidfowl commented on Mar 31, 2021

    @davidfowl
    Member

    Unfortunately this is by design, at least currently without other bigger changes to the runtime. When the process is being torn down we block the event handler until the host is dispose. RunAsync and Run automatically unblock the waiting so code will not execute after it (

    ). That's what disposing the host does.

    @ericstj That issue you mentioned is similar but windows specific. With this one, SIGTERM does trigger process exit but once the host is disposed, it will unwind.

    @martyt

    To work around this you'd need to write code like this:

    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.WaitForShutdownAsync();
    
            Console.WriteLine("Main: RunAsync has completed");
        }
        finally
        {
            Console.WriteLine("Main: stopping");
    
            if (host is IAsyncDisposable d) await d.DisposeAsync();
        }
    }
  18. martyt commented on Mar 31, 2021

    @martyt
    Author

    @davidfowl Thanks for the suggested workaround, but it looks like the call to host.RunAsync() is missing.

    So I added that call (without awaiting, which makes me feel dirty...) and then after adding the await host.WaitForShutdownAsync(), the app performed as I would expect -- control returned to Main() and all of the shutdown / cleanup code was executed:

    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: StopAsync called...
    backgroundservicetest_1  | Worker: OperationCanceledException caught...
    backgroundservicetest_1  | Worker: ExecuteAsync is terminating...
    backgroundservicetest_1  | Main: RunAsync has completed
    backgroundservicetest_1  | Main: stopping
    backgroundservicetest_1  | Worker: Dispose called...
    backgroundservicetest_backgroundservicetest_1 exited with code 0
    
  19. davidfowl commented on Mar 31, 2021

    @davidfowl
    Member

    Ah I forgot to call StartAsync in my sample. You don't want to call RunAsync because it could dispose without you observing it explicitly. With the pattern below you control disposal.

    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();
        }
    }
  20. martyt commented on Mar 31, 2021

    @martyt
    Author

    @davidfowl Thanks, that seems like a perfectly reasonable workaround. (I still think .RunAsync() should return control to the caller, but that's less important to me than having a way to achieve the result that I need...)

  21. davidfowl commented on Mar 31, 2021

    @davidfowl
    Member

    Agreed. Closing this in favor of #50527

  22. ghost locked as resolved and limited conversation to collaborators on May 1, 2021
  23. added 2 commits that reference this issue on Jul 20, 2021
    280e63e
    36f3f97
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-Extensions-Hostingbugneeds-further-triage

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions