Home > Software engineering >  BackgroundService not blocking start of application
BackgroundService not blocking start of application

Time:02-05

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?

CodePudding user response:

Move the

// do some work code

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

CodePudding user response:

It depends on how your application is wired. If you are using the default setup 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.

Potentially you can consider other approach with 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).

  • Related