Skip to content

Generic Host is not stopped when BackgroundService crashes #43637

Closed

Description

@marcselis

Updated by @maryamariyan:

Description:

We want to add a new opt-in option on HostOptions that reacts to failures on a background service.

It generally might not be always desirable to allow for a failure/crash on a background service to stop the application altogether and therefore logging the failure is a default behavior.

API Proposal:

API below would add the option to stop the host on background service exception.

namespace Microsoft.Extensions.Hosting
{
    public class HostOptions
    {
        public bool StopOnBackgroundServiceException { get; set; }
    }
}
Original Description (click to view)

Description

According to the documentation of the BackgroundService.ExecuteAsync method that method should return a Task that represents the lifetime of the long running operation(s) being performed.

For me that implies that this Task is monitored by the generic host, so I would expect that when the BackgroundService.ExecuteAsync's Task instance is completed (successfully or due to an exception) the host itself would also stop. This is not the case. As a result, a Windows service where the BackgroundService.ExecuteAsync method has crashed or stopped will continue to appear running in the Services Management Console, but will no longer be performing any work., causing all monitoring systems to keep reporting that everything is ok.

Configuration

  • .NET Core 3.1.402
  • OS Windows 10.0.18363
  • Architecture X64

Sample application

The following sample demonstrates the problem. You can either run it on the console or install it as windows service and start it. The program will continue to run after the background service has crashed.

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

namespace WorkerTest
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

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

    public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;
        private int _counter;

        public Worker(ILogger<Worker> logger)
        {
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                while (!stoppingToken.IsCancellationRequested)
                {
                    _logger.LogInformation("Worker running at: {time} ({counter})", DateTimeOffset.Now, _counter++);
                    if (_counter > 10)
                        throw new Exception("Something happened!");
                    await Task.Delay(1000, stoppingToken).ConfigureAwait(false);
                }
            }
            finally
            {
                if (!stoppingToken.IsCancellationRequested)
                    _logger.LogError("Worker stopped unexpectedly");
            }
        }
    }

}

Activity

  1. added
    untriaged
    on Oct 20, 2020
  2. maryamariyan commented on Oct 20, 2020

    @maryamariyan
    Contributor

    I don't think the lifetime of Generic Host depends on what its background services do and therefore what you see is an expected outcome.

  3. cwe1ss commented on Oct 20, 2020

    @cwe1ss
    Contributor

    We are using the following base class for background services that should terminate the application on error:

    public abstract class TerminatingBackgroundService : BackgroundService
    {
        protected IServiceProvider ApplicationServices { get; }
        protected IHostApplicationLifetime ApplicationLifetime { get; }
        protected ILogger Logger { get; }
    
        protected TerminatingBackgroundService(IServiceProvider applicationServices)
        {
            ApplicationServices = applicationServices;
            ApplicationLifetime = applicationServices.GetRequiredService<IHostApplicationLifetime>();
            Logger = ApplicationServices.GetRequiredService<ILoggerFactory>().CreateLogger(GetType());
        }
    
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                await ExecuteCoreAsync(stoppingToken);
    
                Logger.LogInformation("Execute has finished. IsCancellationRequested: {IsCancellationRequested}", stoppingToken.I
            }
            catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
            {
                // We're shutting down already, so we don't have to do anything else.
                Logger.LogInformation("OperationCanceledException on shutdown");
            }
            catch (Exception exception)
            {
                Logger.LogCritical(exception, exception.Message);
    
                // We need StopApplication() so that it properly flushes and disposes the logging system.
                // However, it is a graceful shutdown that exits with code 0.
                Environment.ExitCode = 1;
    
                if (!stoppingToken.IsCancellationRequested)
                {
                    ApplicationLifetime.StopApplication();
                }
            }
        }
    
        protected abstract Task ExecuteCoreAsync(CancellationToken stoppingToken);
    }
  4. marcselis commented on Oct 20, 2020

    @marcselis
    Author

    How can it be an "exepcted outcome" that the host process continues to run when the background service doing the actual work has crashed without the host process even knowing? This is a very dangerous situation where all monitoring systems that monitor running Windows services report that everything is OK while no work is being performed.

    As the host is unaware that the worker service has stopped it also cannot take any corrective actions like restarting the worker and/or reporting the error...

  5. maryamariyan commented on Oct 20, 2020

    @maryamariyan
    Contributor
  6. eerhardt commented on Oct 20, 2020

    @eerhardt
    Member

    In .NET 6 we have fixed #36017. Now when an exception is thrown from a BackgroundService, it will get logged as an error.

  7. marcselis commented on Oct 20, 2020

    @marcselis
    Author

    Just logging the exception is not enough. This will still have the same effect: the process keeps running but doesn't perform any work anymore, causing all monitoring systems to think that everything is ok, unless you have some alerting system on your logs.

    I agree with @GeeWee in #36388 (comment) that you should be able to specify (per BackgroundService) what the host should do when that BackgroundService stops, as some background services are more important than others. My options would be: ignore, restart and stop the host with a (specifiable) error code.

  8. maryamariyan commented on Oct 20, 2020

    @maryamariyan
    Contributor

    As per @davidfowl 's comment in #36388 (comment) there could be a new opt-in option on HostOptions that reacts to failures on a background service.

    It generally might not be always desirable to allow for a failure/crash on a background service to stop the application altogether and therefore logging the failure is a default behavior.

  9. davidfowl commented on Jan 18, 2021

    @davidfowl
    Member

    Lets do this for 6.0. Add the option to stop the host on background service exception.

    namespace Microsoft.Extensions.Hosting
    {
        public class HostOptions
        {
            public bool StopOnBackgroundServiceException { get; set; }
        }
    }

    cc @maryamariyan @eerhardt @ericstj

  10. removed
    untriaged
    on Jan 18, 2021
  11. added this to the 6.0.0 milestone on Jan 18, 2021
  12. added
    api-ready-for-review
    on Jan 18, 2021
  13. GeeWee commented on Jan 19, 2021

    @GeeWee

    I think this is a pretty good API suggestion. I would like to suggest that it either

    • Defaults to true (which is a breaking change, but will match the mental model of most programmers that haven't hit this behaviour before)
    • Is required, so you have to set it (not a breaking change, little more verbose, but does force the user to know what's going on.
  14. 25 remaining items

  15. davidfowl commented on Feb 3, 2021

    @davidfowl
    Member

    When I commented out app.UseDeveloperExceptionPage(); in Startup.cs the response have http status code 500 and the browser shows a generic error page.

    That's because the server is doing you a solid and preventing your application from crashing.

    I don't see the problem with this, it's usually a good thing to fail fast on unknown errors instead of keep running and hope that whatever error occurred won't for example corrupt any data. The BCL is taking on a big responsibility here that the rest of the application won't be affected.

    Easy to say that when logging is configured. I'm sure people would be annoyed if their application died without a trace. No logs, no crash dump.

    (From Best practices for exceptions)

    This doesn't apply.

  16. marhja commented on Feb 3, 2021

    @marhja

    Easy to say that when logging is configured. I'm sure people would be annoyed if their application died without a trace. No logs, no crash dump.

    I'm certainly annoyed when my background service die without a trace now in .NET 5. 😅 I think it would be preferable that an unhandled exception in the background service would be propagated to the application, but I guess that's not possible. Then logging the exception and shutting down the application as suggested is acceptable.

  17. davidfowl commented on Feb 3, 2021

    @davidfowl
    Member

    Right, it was impossible to be because nothing was tracking the background task itself and that's why it had it be done by the instance and not the host.

    Raising it to the application would mean some sort of OnBackgroundSericeUnhandledException event?

  18. marhja commented on Feb 3, 2021

    @marhja

    Such an event would not help much since it requires that the developer adds a handler.

  19. davidfowl commented on Feb 3, 2021

    @davidfowl
    Member

    Unfortunately there's no practical way to make the application aware other than to crash

  20. marhja commented on Feb 3, 2021

    @marhja

    What do you mean by "crash"? Process.Kill()? Environment.FailFast()? I thought the idea was a graceful application shutdown using IHostApplicationLifetime.StopApplication().

  21. davidfowl commented on Feb 4, 2021

    @davidfowl
    Member

    The current plan is to do that yes, which will in most cases unblock main and will quit the program.

  22. pinkfloydx33 commented on Feb 26, 2021

    @pinkfloydx33

    I'm a bit hard pressed to think of a specific case at the moment, but one of the comments above got me thinking...

    Would it be possible to have a default value on the HostOptions and then some optional way to specify it on a per-service level? I'm sure there could be services that you may be OK ignoring as they might not be mission critical while others should tear down the app. I don't know how you'd track/register such a thing though. You wouldn't want it as a property on the service class/interface since lib authors could potentially control your app's lifetime but there's also no way to specify the option in an AddHostedService call since it's just adding to the service collection.

    I'm sure the current API is fine for now and it doesn't seem like it would preclude such an enhancement in the future. Just throwing it out there....

  23. IEvangelist commented on Mar 31, 2021

    @IEvangelist
    Member

    I see this is up-for-grabs - I'm interested in working on this one, are you okay with me assigning it to myself @maryamariyan and @eerhardt?

  24. eerhardt commented on Mar 31, 2021

    @eerhardt
    Member

    @IEvangelist - I assigned it to you. Thanks for taking this. I'm looking forward to seeing it being completed.

  25. ghost added
    in-pr
    on Apr 1, 2021
  26. ghost removed
    in-pr
    on Apr 16, 2021
  27. ghost locked as resolved and limited conversation to collaborators on May 16, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

api-approvedarea-Extensions-Hostinghelp wanted

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions