Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inherit BackgroundService and Dispose()

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)?

like image 812
tymtam Avatar asked Jan 03 '23 07:01

tymtam


2 Answers

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
}
like image 183
Piotr Perak Avatar answered Jan 12 '23 23:01

Piotr Perak


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.

like image 24
Joey Cai Avatar answered Jan 12 '23 22:01

Joey Cai