I'm looking at BackgroundService
from Implement background tasks in microservices with IHostedService and the BackgroundService class
The class that I'm converting to inherit from BackgroundService
implemented IDisposable
.
Since Dispose(bool disposing)
is not exposed by BackgroundService
I cannot call base.Dispose(disposing);
in my service's Dispose(bool disposing)
.
Is the idea that classes that inherit from BackgroundService
cleanup in StopAsync
(or have the cleanup code in ExecuteAsync
)?
BackgroundService
contains this code in StopAsync
/// <summary>
/// Triggered when the application host is performing a graceful shutdown.
/// </summary>
/// <param name="cancellationToken">Indicates that the shutdown process should no longer be graceful.</param>
public virtual async Task StopAsync(CancellationToken cancellationToken)
{
if (this._executingTask == null)
return;
try
{
this._stoppingCts.Cancel();
}
finally
{
Task task = await Task.WhenAny(this._executingTask, Task.Delay(-1, cancellationToken));
}
}
Thus this is the way to do cleanup when you inherit from BackgroundService
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
// here you register to be notified when stoppingToken is Canceled in BackgroundService
stoppingToken.Register(ShutDown);
// start some work
return Task.CompletedTask;
}
private void ShutDown()
{
// Cleanup here
}
The
IHostedService
background task execution is coordinated with the lifetime of the application (host or microservice, for that matter). You register tasks when the application starts and you have the opportunity to do some graceful action or clean-up when the application is shutting down.
The ExecuteAsync
register tasks when the application start. By default, the cancellation token is set with 5 second timeout.
This means our service is expected to cancel within 5 seconds otherwise it will be more abruptly killed.
Triggered when the application host is performing a graceful shutdown.
When you ExecuteAsync
shutdown it will trigger the StopAsync
task.
And the you could run your graceful clean up actions in StopAsync . If you do not override the StopAsync in the class that inherit from BackgroundService, it will execute the StopAsync method in BackgroundService.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With