简体   繁体   中英

BackgroundService StopAsync not called when stopping Web App in Azure using ASP.NET Core 6 Minimal API

I created the template Minimal API template with VS 2022 ASP.NET 6.0, and added a BackgroundService as a HostedService. I deployed this to Azure and it starts the Background service fine and i can see it in the logs.

However when i stop the web app in Azure, the StopAsync of the BackgroundService is not called. Do i need to hook something up in the Program.cs with the builder.Host? How in the code can i get notified that the web app is shutting down in case i need to do some other graceful shutdown?

Program.cs

using MinAPI.Test.Workers;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddHostedService<Worker>();

var app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI();

app.UseHttpsRedirection();

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
    var forecast = Enumerable.Range(1, 5).Select(index =>
       new WeatherForecast
       (
           DateTime.Now.AddDays(index),
           Random.Shared.Next(-20, 55),
           summaries[Random.Shared.Next(summaries.Length)]
       ))
        .ToArray();
    return forecast;
})
.WithName("GetWeatherForecast");

app.Run();

internal record WeatherForecast(DateTime Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

Worker.cs

namespace MinAPI.Test.Workers
{
    public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;

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

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                await Task.Delay(1000, stoppingToken);
            }

            _logger.LogInformation("Worker cancellation token finished ");
        }

        public override Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogWarning("Worker STARTING");
            return base.StartAsync(cancellationToken);
        }

        public override Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogWarning("Worker STOPPING: {time}", DateTimeOffset.Now);
            return base.StopAsync(cancellationToken);
        }
    }
}

在此处输入图像描述

Using your code for testing, I found that I can only reproduce your error once, which is exactly the same as your screenshot.

Then I try to redeploy it, and I found it disappeared. Below log is on myside.

2021-12-20 05:48:53.068 +00:00 [Information] Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager: Azure Web Sites environment detected. Using 'C:\home\ASP.NET\DataProtection-Keys' as key repository; keys will not be encrypted at rest.
2021-12-20 05:48:54.116 +00:00 [Warning] dotnet5.Worker: Worker STARTING
2021-12-20 05:48:54.137 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:48:54 +00:00
2021-12-20 05:48:55.148 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:48:55 +00:00
2021-12-20 05:48:56.164 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:48:56 +00:00
2021-12-20 05:48:56.364 +00:00 [Information] Microsoft.Hosting.Lifetime: Application started. Press Ctrl+C to shut down.
2021-12-20 05:48:56.364 +00:00 [Information] Microsoft.Hosting.Lifetime: Hosting environment: Production
2021-12-20 05:48:56.364 +00:00 [Information] Microsoft.Hosting.Lifetime: Content root path: C:\home\site\wwwroot
2021-12-20 05:48:56.674 +00:00 [Information] Microsoft.AspNetCore.Hosting.Diagnostics: Request starting HTTP/1.1 GET https://test.azurewebsites.net/
2021-12-20 05:48:57.163 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:48:57 +00:00
2021-12-20 05:48:57.329 +00:00 [Information] Microsoft.AspNetCore.Routing.EndpointMiddleware: Executing endpoint 'dotnet5.Controllers.HomeController.Index (dotnet5)'
2021-12-20 05:48:57.724 +00:00 [Information] Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker: Route matched with {action = "Index", controller = "Home", page = "", area = ""}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Index() on controller dotnet5.Controllers.HomeController (dotnet5).
2021-12-20 05:48:57.852 +00:00 [Information] Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker: Executing action method dotnet5.Controllers.HomeController.Index (dotnet5) - Validation state: Valid
2021-12-20 05:48:57.872 +00:00 [Information] Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker: Executed action method dotnet5.Controllers.HomeController.Index (dotnet5), returned result Microsoft.AspNetCore.Mvc.ViewResult in 2.9601ms.
2021-12-20 05:48:58.054 +00:00 [Information] Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor: Executing ViewResult, running view Index.
2021-12-20 05:48:58.178 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:48:58 +00:00
2021-12-20 05:48:59.195 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:48:59 +00:00
2021-12-20 05:48:59.534 +00:00 [Information] Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor: Executed ViewResult - view Index executed in 1609.7136ms.
2021-12-20 05:48:59.544 +00:00 [Information] Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker: Executed action dotnet5.Controllers.HomeController.Index (dotnet5) in 1808.7693ms
2021-12-20 05:48:59.552 +00:00 [Information] Microsoft.AspNetCore.Routing.EndpointMiddleware: Executed endpoint 'dotnet5.Controllers.HomeController.Index (dotnet5)'
2021-12-20 05:48:59.583 +00:00 [Information] Microsoft.AspNetCore.Hosting.Diagnostics: Request finished in 2937.7265ms 200 text/html; charset=utf-8
2021-12-20 05:49:00.210 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:49:00 +00:00
2021-12-20 05:49:01.226 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:49:01 +00:00
2021-12-20 05:49:02.242 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:49:02 +00:00
2021-12-20 05:49:03.257 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:49:03 +00:00
2021-12-20 05:49:04.273 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:49:04 +00:00
2021-12-20 05:49:05.288 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:49:05 +00:00
2021-12-20 05:49:06.304 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:49:06 +00:00
2021-12-20 05:49:07.319 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:49:07 +00:00
2021-12-20 05:49:08.335 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:49:08 +00:00
2021-12-20 05:49:09.351 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:49:09 +00:00
2021-12-20 05:49:09.820 +00:00 [Information] Microsoft.Hosting.Lifetime: Application is shutting down...
👉2021-12-20 05:49:09.843 +00:00 [Warning] dotnet5.Worker: Worker STOPPING: 12/20/2021 05:49:09 +00:00
SnapshotUploader.exe Information: 0 : SnapshotUploader version 1.3.7.5 (x86) started.DateTime=2021-12-20T05:49:00.1939386ZSnapshotUploader.exe Information: 0 : Previous log file moved to C:\home\LogFiles\SnapshotUploader_c01540_20211220_054724.logDateTime=2021-12-20T05:49:00.1939386Z
SnapshotUploader.exe Information: 0 : Using AI ingestion endpoint: https://centralus-2.in.applicationinsights.azure.com//v2/trackDateTime=2021-12-20T05:49:00.2407520ZSnapshotUploader.exe Information: 0 : Using endpoint: https://agent.azureserviceprofiler.net/DateTime=2021-12-20T05:49:00.2563780ZSnapshotUploader.exe Information: 0 : [PII]Using iKey: a131ce6d-e7f6-451e-8f0c-2db3f2ad0bf0DateTime=2021-12-20T05:49:00.2563780ZSnapshotUploader.exe Information: 0 : Snapshot feature version: 1.0.0DateTime=2021-12-20T05:49:00.2563780ZSnapshotUploader.exe Information: 0 : Enabling site extension version: 3.13.2110.1201DateTime=2021-12-20T05:49:00.2563780ZSnapshotUploader.exe Information: 0 : Monitoring process 21104 for exit.DateTime=2021-12-20T05:49:00.4751823ZSnapshotUploader.exe Information: 0 : Scanning C:\home\site\wwwroot for local PDBs.DateTime=2021-12-20T05:49:03.4908425ZSnapshotUploader.exe Information: 0 : Scanning C:\Program Files (x86)\SiteExtensions\DiagnosticServices\3.13.2110\components\SnapshotCollector\1.3.7.5\core\netcoreapp3.0 for local PDBs.DateTime=2021-12-20T05:49:03.5065455ZSnapshotUploader.exe Information: 0 : Local PDB scan complete. Found 2 PDB(s).DateTime=2021-12-20T05:49:03.5065455ZSnapshotUploader.exe Information: 0 : Snapshot uploader successfully started. Using folder C:\local\Temp\Dumps\a131ce6de7f6451e8f0c2db3f2ad0bf0 for dump files.DateTime=2021-12-20T05:49:03.5377240ZSnapshotUploader.exe Information: 0 : SnapshotHolder listening on named pipe SnapshotUploader/ffa525a65d956d1f737e0e7e214c68deDateTime=2021-12-20T05:49:03.9127268ZSnapshotUploader.exe Information: 0 : Received Shutdown request from process 21104DateTime=2021-12-20T05:49:09.9786460ZSnapshotUploader.exe Information: 0 : Shutdown request from process 21104.DateTime=2021-12-20T05:49:09.9908695ZSnapshotUploader.exe Information: 0 : Stopped watching minidump folder. Draining snapshot holder queue.DateTime=2021-12-20T05:49:10.0065465ZSnapshotUploader.exe Information: 0 : Snapshot uploader exiting.DateTime=2021-12-20T05:49:10.0377999ZSnapshotUploader.exe Information: 0 : SnapshotHolder server exiting due to cancelation.DateTime=2021-12-20T05:49:10.0533711Z
2021-12-20T05:49:15 sandboxproc.exe D:\DWASFiles\Sites\#1test\Temp\applicationhost.config False True
2021-12-20T05:49:15 env XPROC_TYPENAME=Microsoft.Web.Hosting.Transformers.ApplicationHost.SiteExtensionHelper, Microsoft.Web.Hosting, Version=7.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
2021-12-20T05:49:15 env XPROC_METHODNAME=Transform
2021-12-20T05:49:16 Start 'Microsoft.AspNetCore.AzureAppServices.SiteExtension' site extension transform
2021-12-20T05:49:16 Successful 'C:\home\SiteExtensions\Microsoft.AspNetCore.AzureAppServices.SiteExtension\scmApplicationHost.xdt' site extension transform
2021-12-20T05:49:16 sandboxproc.exe complete successfully. Elapsed = 318.00 ms
2021-12-20T05:51:15  No new trace in the past 1 min(s).
2021-12-20T05:52:15  No new trace in the past 2 min(s).
2021-12-20T05:53:15  No new trace in the past 3 min(s).

So I think your code is correct. Test code on my side which is same as you.

在此处输入图像描述

I have had a similar issue:

  • added a hosted service: services.AddHostedService<XXXWorker>(); in Configure
  • all the usual other stuff to configure controllers.
  • IIS site configured to preload and start automatically.

and found the hosted service would start automatically as soon as the AppPool was started, but was never getting any of the calls to shutdown when it was stopped.

What I have discovered is that this only happens if there have never been any web requests to the controller(s). If at least one has been made, then it all works just as you would expect.

Don't know if this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM