dotnet / dotnet/aspnetcore

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

Open
#39,139 16 comments 2 reactions 1 assignee Claimed by @bradygaster View on GitHub
area-networking investigate
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

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();

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 _logger;

public Worker(ILogger 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);
}
}
}
```
![image](https://user-images.githubusercontent.com/82517603/146975784-550c4f1e-3235-4ae5-83d5-d23ac63de133.png)

### Expected Behavior

I would expect the line _logger.LogWarning("Worker STOPPING: {time}", DateTimeOffset.Now); to be hit when stopping in Azure.

### Steps To Reproduce

_No response_

### Exceptions (if any)

_No response_

### .NET Version

.Net 6

### Anything else?

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.