Repository navigation
Description
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
maryamariyan commentedon Oct 20, 2020
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.
cwe1ss commentedon Oct 20, 2020
We are using the following base class for background services that should terminate the application on error:
marcselis commentedon Oct 20, 2020
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...
maryamariyan commentedon Oct 20, 2020
Related to #36388 (comment) and #36388 (comment)
eerhardt commentedon Oct 20, 2020
In .NET 6 we have fixed #36017. Now when an exception is thrown from a BackgroundService, it will get logged as an error.
marcselis commentedon Oct 20, 2020
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.
maryamariyan commentedon Oct 20, 2020
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.
davidfowl commentedon Jan 18, 2021
Lets do this for 6.0. Add the option to stop the host on background service exception.
cc @maryamariyan @eerhardt @ericstj
GeeWee commentedon Jan 19, 2021
I think this is a pretty good API suggestion. I would like to suggest that it either
true(which is a breaking change, but will match the mental model of most programmers that haven't hit this behaviour before)25 remaining items
davidfowl commentedon Feb 3, 2021
That's because the server is doing you a solid and preventing your application from crashing.
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.
This doesn't apply.
marhja commentedon Feb 3, 2021
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.
davidfowl commentedon Feb 3, 2021
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?
marhja commentedon Feb 3, 2021
Such an event would not help much since it requires that the developer adds a handler.
davidfowl commentedon Feb 3, 2021
Unfortunately there's no practical way to make the application aware other than to crash
marhja commentedon Feb 3, 2021
What do you mean by "crash"?
Process.Kill()?Environment.FailFast()? I thought the idea was a graceful application shutdown usingIHostApplicationLifetime.StopApplication().davidfowl commentedon Feb 4, 2021
The current plan is to do that yes, which will in most cases unblock main and will quit the program.
pinkfloydx33 commentedon Feb 26, 2021
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
HostOptionsand 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 anAddHostedServicecall 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....
IEvangelist commentedon Mar 31, 2021
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?eerhardt commentedon Mar 31, 2021
@IEvangelist - I assigned it to you. Thanks for taking this. I'm looking forward to seeing it being completed.