继承 BackgroundService 和 Dispose()

tym*_*tam 4 c# idisposable azure

我期待在BackgroundService与IHostedService和BackgroundService类微服务实现后台任务

我要转换为从BackgroundService实现的继承的类IDisposable

由于Dispose(bool disposing)没有被暴露,BackgroundService我无法调用base.Dispose(disposing);我的服务的Dispose(bool disposing).

是从BackgroundService清除中继承的类StopAsync(或在 中具有清除代码ExecuteAsync)的想法吗?

Pio*_*rak 7

BackgroundService 包含此代码 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));
  }
}
Run Code Online (Sandbox Code Playgroud)

因此,这是从继承时进行清理的方法 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
}
Run Code Online (Sandbox Code Playgroud)