I have a few background jobs in my application that modify the database on an interval (from a few minutes to several hours). All of them have a while
loop that uses the stoppingToken.IsCancellationRequested
condition.
Currently I am creating and disposing a scope inside the loop, which means on every iteration, a scope needs to be created and disposed. My question is that from a performance and security point of view where should I create my scope? Inside the loop for each iteration or outside the loop once in the application lifetime?
public class MyBackgroundJob : BackgroundService
{
private readonly IServiceProvider _serviceProvider;
public MyBackgroundJob(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// Here?
//using var scope = _serviceProvider.CreateScope();
//var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
while (!stoppingToken.IsCancellationRequested)
{
// Or here?
using var scope = _serviceProvider.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
// Do some work
try
{
await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
}
catch (TaskCanceledException)
{
// application is shutting down
// ignore this
}
}
}
}