简体   繁体   English

使用 ASP.NET 核心 6 最小 ZDB93474238D104CAADE1 停止 Azure 中的 Web 应用程序时未调用 BackgroundService StopAsync

[英]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.我使用 VS 2022 ASP.NET 6.0 创建了模板 Minimal API 模板,并将 BackgroundService 添加为 HostedService。 I deployed this to Azure and it starts the Background service fine and i can see it in the logs.我将它部署到 Azure 并启动后台服务正常,我可以在日志中看到它。

However when i stop the web app in Azure, the StopAsync of the BackgroundService is not called.但是,当我在 Azure 中停止 web 应用程序时,不会调用 BackgroundService 的 StopAsync。 Do i need to hook something up in the Program.cs with the builder.Host?我需要将 Program.cs 中的某些内容与 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?我如何在代码中收到 web 应用程序正在关闭的通知,以防我需要进行其他正常关闭?

Program.cs程序.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工人.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>();添加了托管服务: services.AddHostedService<XXXWorker>(); in Configure在配置中
  • all the usual other stuff to configure controllers.配置控制器的所有其他常见内容。
  • IIS site configured to preload and start automatically. IIS 站点配置为预加载并自动启动。

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.并发现托管服务将在 AppPool 启动后立即自动启动,但在停止时从未收到任何关闭调用。

What I have discovered is that this only happens if there have never been any web requests to the controller(s).我发现只有在从未向控制器发出任何 web 请求时才会发生这种情况。 If at least one has been made, then it all works just as you would expect.如果至少制作了一个,那么一切都将按照您的预期进行。

Don't know if this helps.不知道这是否有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 asp.NET Core timed BackgroundService 不能在 Controller 中使用 StopAsync() 停止 - asp.NET Core timed BackgroundService cannot be stopped in Controller with StopAsync() ASP.NET 最小内核 6 web API 部署到 Z5DA5ACF461B4EFB7E26EC86106Z5B21 - ASP.NET Core 6 Minimal web API Deploy To IIS 在 ASP.NET 中运行单独的进程 核心 Web 最小 API - Running separate process in ASP.NET Core Web Minimal API 如何使用身份向 ASP.NET 核心最小 API 添加身份验证,但不使用 Azure? - How do I add authentication to an ASP.NET Core minimal API using Identity, but without using Azure? Azure上的Asp.Net Core Web API - Asp.Net Core Web API on Azure ASP.Net core 3.1中如何启动BackgroundService API - How to start BackgroundService in ASP.Net core 3.1 API .NET 5 WindowsService with ASP.NET Core and BackgroundService - .NET 5 WindowsService with ASP.NET Core and BackgroundService 在使用最小 api 时在服务配置期间访问 ASP.NET 核心设置 - Access ASP.NET Core settings during service configuration when using minimal api 为什么停止 IHost 时会调用两次 StopAsync? - Why is StopAsync called twice when stopping IHost? 一个使用 Azure AD B2C 的多个客户端 ID(应用程序 ID)的 ASP.NET Core 2.2 Web API 应用程序 - One ASP.NET Core 2.2 Web API app Using Multiple Client IDs (Application IDs) of Azure AD B2C
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM