我正在查看来自 Implement background tasks in microservices with IHostedService and the BackgroundService classBackgroundService
我要转换为从 BackgroundService 继承的类实现了 IDisposable

由于 Dispose(bool disposing) 未由 BackgroundService 公开,因此我无法在服务的 base.Dispose(disposing); 中调用 Dispose(bool disposing)

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

最佳答案

BackgroundServiceStopAsync 中包含此代码

/// <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));
  }
}

因此,这是从 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
}

关于c# - 继承 BackgroundService 和 Dispose(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50715275/

10-12 07:20