My ASP.NET Core Razor website doesn't open in a browser when I add a BackgroundService

Advertisements

I have created ASP.NET Core Web App (Razor Pages). I start it without any problems and it opens in a browser but when I add a BackgroundService:

public class BackgroundJob : BackgroundService
{
    public BackgroundJob()
    {
    }

    protected async override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {

        }
    }
}

    // In Program.cs:
    builder.Services.AddHostedService<BackgroundJob>();

then my website doesn’t want to open in a browser when I run the application (no errors), why?

>Solution :

You didn’t post your complete ExecuteAsync code but I guess you are hitting this issue:

https://github.com/dotnet/runtime/issues/36063

Adding await Task.Yield() to the top of the ExecuteAsync() probably would fix it:

protected async override Task ExecuteAsync(CancellationToken stoppingToken)
{
    await Task.Yield();

    while (!stoppingToken.IsCancellationRequested)
    {

    }
}

Leave a ReplyCancel reply