filur
filur

Reputation: 1576

BackgroundService not blocking start of application

I have a background service in my net 7 web api application:

public class MyBackgroundService : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            using var scope = _provider.CreateScope();
            // do some work
            await Task.Delay(60000, stoppingToken);
        }
    }
}

Which I register like this:

services.AddHostedService<MyBackgroundService>();

How can I make it blocking so that the rest of my application doesn't start before the first do some work is executed?

Upvotes: 1

Views: 1477

Answers (2)

Guru Stron
Guru Stron

Reputation: 143138

It depends on how your application is wired. If you are using the default setup (for ASP.NET Core 7th version) then background services should be started up before the rest of the app and you can just override the BackgroundService.StartAsync (or just implement IHostedService directly) and perform first "do some work code" (potentially moving it to separate method) invocation in blocking manner (i.e. use blocking calls via Task.Result or Task.Wait(...) for async methods). Also do not forget to register this "blocking" hosted service first if you have multiple ones.

If you do not want to rely on the default order or you are using setup which has different order of startup (for example see this) then I would recommend to move the "do some work code" in some service, resolve it and invoke it before the app run:

var app = builder.Build();
// ...
var service = app.Services.GetRequiredService<IMyService>(); // create scope if needed
await service.DoSomeWorkCode(); // first run
app.Run();

P.S.

Also you can consider adding readiness probe to your app and middleware which will intercept all other requests if app is not ready (i.e. the initial run of "do some work code" has not finished).

Upvotes: 2

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89386

Move the

// do some work code

into a separate method so you can call it at startup.

Upvotes: 2

Related Questions