Skip to content

Commit

Permalink
Check BackgroundService.ExecuteTask for null
Browse files Browse the repository at this point in the history
In some scenarios, derived classes might not have called base.StartAsync, and ExecuteTask will still be null. Ensure we don't fail in those cases.

Fix dotnet#60131
  • Loading branch information
eerhardt committed Oct 7, 2021
1 parent 05345b2 commit 15c827d
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 14 deletions.
33 changes: 19 additions & 14 deletions src/libraries/Microsoft.Extensions.Hosting/src/Internal/Host.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,24 +79,29 @@ public async Task StartAsync(CancellationToken cancellationToken = default)

private async Task TryExecuteBackgroundServiceAsync(BackgroundService backgroundService)
{
try
// backgroundService.ExecuteTask may not be set (e.g. if the derived class doesn't call base.StartAsync)
Task backgroundTask = backgroundService.ExecuteTask;
if (backgroundTask != null)
{
await backgroundService.ExecuteTask.ConfigureAwait(false);
}
catch (Exception ex)
{
// When the host is being stopped, it cancels the background services.
// This isn't an error condition, so don't log it as an error.
if (_stopCalled && backgroundService.ExecuteTask.IsCanceled && ex is OperationCanceledException)
try
{
return;
await backgroundTask.ConfigureAwait(false);
}

_logger.BackgroundServiceFaulted(ex);
if (_options.BackgroundServiceExceptionBehavior == BackgroundServiceExceptionBehavior.StopHost)
catch (Exception ex)
{
_logger.BackgroundServiceStoppingHost(ex);
_applicationLifetime.StopApplication();
// When the host is being stopped, it cancels the background services.
// This isn't an error condition, so don't log it as an error.
if (_stopCalled && backgroundTask.IsCanceled && ex is OperationCanceledException)
{
return;
}

_logger.BackgroundServiceFaulted(ex);
if (_options.BackgroundServiceExceptionBehavior == BackgroundServiceExceptionBehavior.StopHost)
{
_logger.BackgroundServiceStoppingHost(ex);
_applicationLifetime.StopApplication();
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1394,6 +1394,36 @@ public async Task HostNoErrorWhenServiceIsCanceledAsPartOfStop()
}
}

/// <summary>
/// Tests that when a BackgroundService does not call base, the Host still starts and stops successfully.
/// </summary>
[Fact]
public async Task StartOnBackgroundServiceThatDoesNotCallBase()
{
TestLoggerProvider logger = new TestLoggerProvider();

using IHost host = CreateBuilder()
.ConfigureLogging(logging =>
{
logging.AddProvider(logger);
})
.ConfigureServices(services =>
{
services.AddHostedService<BackgroundServiceDoesNotCallBase>();
})
.Build();

host.Start();
await host.StopAsync();

foreach (LogEvent logEvent in logger.GetEvents())
{
Assert.True(logEvent.LogLevel <= LogLevel.Information, "All logged events should be les than or equal to Information. No Warnings or Errors.");

Assert.NotEqual("BackgroundServiceFaulted", logEvent.EventId.Name);
}
}

private IHostBuilder CreateBuilder(IConfiguration config = null)
{
return new HostBuilder().ConfigureHostConfiguration(builder => builder.AddConfiguration(config ?? new ConfigurationBuilder().Build()));
Expand Down Expand Up @@ -1562,5 +1592,14 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
}
}
}

private class BackgroundServiceDoesNotCallBase : BackgroundService
{
public override Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask;

protected override Task ExecuteAsync(CancellationToken stoppingToken) => Task.CompletedTask;

public override Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
}
}

0 comments on commit 15c827d

Please sign in to comment.