AspNetCore.Docs icon indicating copy to clipboard operation
AspNetCore.Docs copied to clipboard

Web app fails to load when waiting asynchronously inside an IHostedService

Open MarcPilgaard opened this issue 2 years ago • 3 comments

[EDIT by guardrex to add metadata]

In a fresh solution, using the Blazor Web App template with interactive render mode as Server I noticed the example would fail to load if I awaited an asynchronous task inside a hosted IHostedService

In program.cs:

builder.Services.AddHostedService<SomeRandomService>();

Then I'll create the following file:

public class SomeRandomService : IHostedService
{
    public async Task StartAsync(CancellationToken cancellationToken)
    {
        while (true)
        {
            await Task.Delay(10000, cancellationToken);
        }
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        throw new NotImplementedException();
    }
}

But if I converted the service to use BackgroundService instead, it would work as intended:

public class SomeRandomService : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (true)
        {
            await Task.Delay(10000, stoppingToken);
        }
    }
}

Are raw IHostedServices a no-no in Blazor or what am I missing?

Using .NET 8.0.401

Page URL

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-9.0&tabs=visual-studio

Content source URL

https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/fundamentals/host/hosted-services.md

Document ID

b2dece1f-15b8-03af-6d52-7cc070432b4b

Article author

— ... Tom takes care of this one, but I'll place a quick line or two and ping him for review.

MarcPilgaard avatar Oct 22 '24 19:10 MarcPilgaard

Hello @MarcPilgaard ... Please open this for the product unit ...

https://github.com/dotnet/aspnetcore/issues

Please add ...

cc: @guardrex https://github.com/dotnet/AspNetCore.Docs/issues/33902

... to the bottom of your opening comment so that I can follow the discussion.

guardrex avatar Oct 22 '24 21:10 guardrex

@MarcPilgaard ... That's a good explanation from Halter to clear it up.

IHostedService.StartAsync implementations must complete before ASP.NET Core will start accepting requests. This is useful if you need to do something like warm up caches before serving requests. ExecuteAsync is expected to run for the duration of the application.

I'll see if I can update the article to improve the coverage and make that point clear. Scheduling this for work now! 🏃

guardrex avatar Oct 24 '24 20:10 guardrex

I just checked on this. The article states for IHostedService. ...

StartAsync should be limited to short running tasks because hosted services are run sequentially, and no further services are started until StartAsync runs to completion.

... so I think it's covered.

guardrex avatar Oct 25 '24 13:10 guardrex