Skip to content

Web app fails to load when waiting asynchronously inside an IHostedService #33902

@MarcPilgaard

Description

@MarcPilgaard

[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.

Metadata

Metadata

Assignees

Type

No type

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions