Background task dependency injection
Hello,
I tried to use Parallel.ForEach in my backgound task.
my class FactHostedService which is started every ten minutes :
internal class FactHostedService : IHostedService, IDisposable
{
private readonly ILogger _logger;
private Timer _timer;
public FactHostedService(IServiceProvider services, ILogger<FactHostedService> logger)
{
Services = services;
_logger = logger;
}
public IServiceProvider Services { get; }
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Timed Background Service is starting.");
_timer = new Timer(DoWork, null, TimeSpan.Zero,
TimeSpan.FromSeconds(600));
return Task.CompletedTask;
}
private async void DoWork(object state)
{
_logger.LogInformation("Timed Background Service is working.");
using var scope = Services.CreateScope();
var scopedProcessingService = scope.ServiceProvider.GetRequiredService<IFactScopedProcessingService>();
await scopedProcessingService.DoWork();
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Timed Background Service is stopping.");
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
}
my FactScopedProcessingService :
internal interface IFactScopedProcessingService
{
Task DoWork();
}
internal class FactScopedProcessingService : IFactScopedProcessingService
{
private readonly ILogger _logger;
private readonly IFactsRepository _factsRepository;
private readonly IFactsService _factsService;
public FactScopedProcessingService(ILogger<FactScopedProcessingService> logger, IFactsRepository factsRepository, IFactsService factsService)
{
_logger = logger;
_factsRepository = factsRepository ?? throw new ArgumentNullException(nameof(factsRepository));
_factsService = factsService ?? throw new ArgumentNullException(nameof(factsService));
}
public async Task DoWork()
{
_logger.LogInformation("Scoped Processing Service is working.");
var facts = await _factsRepository.GetAllAsyncForScheduledTask();
Parallel.ForEach(facts, async fact =>
{
await _factsRepository.UpdateActualizationLockAsync(fact);
await _factsService.UpdateFactForSheduledTask(fact, fact.DocumentId, fact.ConnectorId, fact.ConnectorBase.ServerLicense.LicenseKey);
});
}
}
and my Startup :
services.AddHostedService<FactHostedService>();
services.AddScoped<IFactScopedProcessingService, FactScopedProcessingService>();
here is the error message when I run :
Unhandled Exception: System.ObjectDisposedException: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'ApplicationDbContext'.
I delete 'using' for scope in FactHostedService :
private async void DoWork(object state)
{
_logger.LogInformation("Timed Background Service is working.");
var scope = Services.CreateScope(); // delete using
var scopedProcessingService = scope.ServiceProvider.GetRequiredService<IFactScopedProcessingService>();
await scopedProcessingService.DoWork();
}
background task runs but I have a warning :
Disposable object created by 'Services.CreateScope()' is never disposed
what is the good practice?
Thanks for your help, Kevin
This is a consequence of Parallel.ForEach where the thread is freed for the duration of the async call. Basically masks an async void which can't be awaited, that's why they are considered bugs. If you are in experimental mode adopt IAsyncEnumerable.
@kcomin It's because you aren't awaiting Parallel.ForEach (you can't await it). I don't think that the suggestion to use IAsyncEnumerable is actually applicable for your code.
You need to use:
await Task.WhenAll(
_factsRepository.UpdateActualizationLockAsync(fact),
_factsService.UpdateFactForSheduledTask(fact, fact.DocumentId, fact.ConnectorId, fact.ConnectorBase.ServerLicense.LicenseKey));
@shaynevanasperen thank you for your guidance.
I placed my functions in Task.WhenAll() :
public async Task DoWork()
{
_logger.LogInformation("Scoped Processing Service is working.");
var facts = await _factsRepository.GetAllAsyncForScheduledTask();
var tasks = facts.Select(async fact => await realoadFact(fact));
await Task.WhenAll(tasks);
}
private async Task realoadFact(FactEntity fact)
{
// if ((DateTime.Now - fact.DataActualizationDate).TotalMinutes >= fact.ActualizationInterval && !fact.ActualizationLock)
// {
// Pass Lock to true
await _factsRepository.LockFactActualizationAsync(fact.Id);
// Update data
// await _factsService.UpdateFactForSheduledTask(fact, fact.DocumentId, fact.ConnectorId, fact.ConnectorBase.ServerLicense.LicenseKey);
// Pass Lock to false
// await _factsRepository.UnlockFactActualizationAsync(fact.Id);
// }
}
But my function LockFactActualizationAsync() makes a SaveChangesAsync() and returns the following exception :
EROR] | [Microsoft.EntityFrameworkCore.Update] An exception occurred in the database while saving changes for context type 'ApplicationDbContext'.
System.InvalidOperationException: A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext, however instance members are not guaranteed to be thread safe. This could also be caused by a nested query being evaluated on the client, if this is the case rewrite the query avoiding nested invocations.
Because I am in the same Context.
@kcomin So don't call SaveChangesAsync() inside LockFactActualizationAsync(). Do it just once afterwards instead. Like this:
public async Task DoWork()
{
_logger.LogInformation("Scoped Processing Service is working.");
var facts = await _factsRepository.GetAllAsyncForScheduledTask();
var tasks = facts.Select(async fact => await realoadFact(fact)); // don't do this await either rather do:
var tasks = facts.Select(fact => realoadFact(fact));
await Task.WhenAll(tasks);
await _dbContext.SaveChangesAsync();
}
private async Task realoadFact(FactEntity fact)
{
// if ((DateTime.Now - fact.DataActualizationDate).TotalMinutes >= fact.ActualizationInterval && !fact.ActualizationLock)
// {
// Pass Lock to true
await _factsRepository.LockFactActualizationAsync(fact.Id); // without calling SaveChangesAsync() inside
// Update data
// await _factsService.UpdateFactForSheduledTask(fact, fact.DocumentId, fact.ConnectorId, fact.ConnectorBase.ServerLicense.LicenseKey);
// Pass Lock to false
// await _factsRepository.UnlockFactActualizationAsync(fact.Id);
// }
}
Closing inactive discussion thread.