【问题标题】:Inherit BackgroundService and Dispose()继承 BackgroundService 和 Dispose()
【发布时间】:2018-11-15 20:05:10
【问题描述】:

我在看BackgroundService 来自Implement background tasks in microservices with IHostedService and the BackgroundService class

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

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

BackgroundService 继承的类是否会在StopAsync 中进行清理(或者在ExecuteAsync 中有清理代码)?

【问题讨论】:

  • 它对StopAsync 表示:“当应用程序主机执行正常关闭时触发。”。我猜你会在那里打扫卫生。
  • 你也可以直接实现IHostedService

标签: c# azure idisposable


【解决方案1】:

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
}

【讨论】:

    【解决方案2】:

    IHostedService 后台任务执行与应用程序(主机或微服务)的生命周期相协调。 您在应用程序启动时注册任务,并且您有机会在应用程序关闭时执行一些优雅的操作或清理。

    ExecuteAsync 在应用程序启动时注册任务。默认情况下,取消令牌设置为 5 秒超时。 这意味着我们的服务预计会在 5 秒内取消,否则会更突然地被杀死。

    在应用程序主机执行正常关闭时触发。

    当你ExecuteAsync 关机时,它会触发StopAsync 任务。

    您可以在 StopAsync 中运行优雅的清理操作。如果不重写继承自BackgroundService的类中的StopAsync,它将执行BackgroundService中的StopAsync方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-07
      • 2015-12-09
      • 1970-01-01
      • 1970-01-01
      • 2013-12-12
      相关资源
      最近更新 更多