Open beppemarazzi opened 1 year ago
Tagging subscribers to this area: @dotnet/area-extensions-hosting See info in area-owners.md if you want to be subscribed.
Author: | beppemarazzi |
---|---|
Assignees: | - |
Labels: | `untriaged`, `area-Extensions-Hosting` |
Milestone: | - |
Probably related with #50019
Perhaps the request here would be to instead have a new value for BackgroundServiceExceptionBehavior which would be to rethrow the exception and let the process exit.
Not sure about rethrowing… it should be enough if you run sc.exe failureflag SERVICENAME 1
at install time and then set ServiceBase.ExitCode = nonzero (e.g. Exception.HResult) during the IHostApplicationLifetime.ApplicationStopped notification if the stop was caused by an error. Hosting will log the original exception anyway, so you don't need to rethrow that for ServiceBase to catch and log.
Description
If there is an unexpected exception into a
BackgroundService
, the Host correctly tears down all the application by default. (see https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.hosting.hostoptions.backgroundserviceexceptionbehavior)The problem is that when the application is executed in a WindowsService through
UseWindowsService
API, the ServiceControlManager is notified of a normal ServiceStop in this case. So it's impossible to configure the SCM to restart the service in case of unexpected termination.Reproduction Steps
var builder = WebApplication.CreateBuilder(options); builder.Host.UseWindowsService(); builder.Services.AddHostedService();
var app = builder.Build();
app.Run();
class MyHS : BackgroundService { private readonly ILogger _logger; public MyHS(ILogger logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Started");
while(!stoppingToken.IsCancellationRequested)
{
if (File.Exists("c:\crash.txt"))
throw new InvalidOperationException("CRASH");
}
Configuration
Microsoft.AspNetCore.App 6.0.10 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
λ [System.Environment]::OSVersion.Version
Major Minor Build Revision
10 0 19043 0
Other information
No response