Skip to content

Missing Logging of Exceptions in IHostedService without await #84559

@Tripletri

Description

@Tripletri

Description

When an exception occures in IHostedService without calling await, it is not logged to the ILogger.
This make it difficult to identify the reason for the application shutdown when writing logs to an external service.

Reproduction Steps

IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.AddHostedService<Worker>();
    })
    .Build();

await host.RunAsync();

public class Worker : IHostedService
{
    public Task StartAsync(CancellationToken cancellationToken) =>
        throw new Exception();

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

Expected behavior

When an exception occurs within the StartAsync of IHostedService, whether or not method has await, the exception should be logged to the ILogger

Actual behavior

When an exception occurs in the StartAsync without calling await, the exception is not logged to the ILogger

Regression?

No response

Known Workarounds

No response

Configuration

Sdk: Microsoft.NET.Sdk.Worker
Framework: .NET 7.0.3

Other information

It is also lead to misunderstanding of BackgroundServiceExceptionBehavior.Ignore, which continue to stop host when exception occurs.

This can be relative to #67146

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions