Closed
Description
Is there an existing issue for this?
- I have searched the existing issues
Describe the bug
The BackgroundService stoppingToken is not triggering instantly when there is a browser session open with a Blazor Server interactive page.
The gracefully shutdown is not happening as expected when doing a Ctrl+C on Console.
The same code work as expected on .net 8
If you navigate to a statically rendered page, the issue does not happens.
// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
builder.Services.AddHostedService<Job>();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseAntiforgery();
app.MapStaticAssets();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
app.Run();
// Job.cs
public class Job(ILogger<Job> logger) : BackgroundService
{
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
return Task.Run(async () =>
{
stoppingToken.Register(() =>
{
// The code here is not calling immediately when Ctrl+C is pressed.
logger.LogInformation("Job is stopping");
});
while (!stoppingToken.IsCancellationRequested)
{
logger.LogInformation("Job is running");
await Task.Delay(1000);
}
}, stoppingToken);
}
}
Expected Behavior
The stoppingToken of all Hosted Service should trigger immediately.
Steps To Reproduce
- Create a new .net 9.0 Blazor Web App Project, choose Interactive render mode = Server and Interactivity location = Global
- Create a background job which inherits from BackgroundService and register it on Program.cs
- Create a while loop on the background service which should stop doing their job when application is closing
- Execute the program and leave a page open on Browser which create a SignalR Blazor circuit
Exceptions (if any)
No response
.NET Version
9.0.101
Anything else?
No response