Jan Hettich
Jan Hettich

Reputation: 9886

How to apply HostOptions.ShutdownTimeout when configuring .NET Core Generic Host?

I am using the .NET Core Generic Host (not Web Host) to build a Console app that needs a rather lengthy graceful shutdown. From the source code in

aspnet/Hosting/src/Microsoft.Extensions.Hosting/HostOptions

it seems pretty clear that the ShutdownTimeout option can be used to change the shutdown timeout in the cancellation token that is provided as a parameter to ShutdownAsync. By default it is 5 seconds.

However, I can't figure out where and how to write the code to specify this option in the HostBuilder configuration code that you typically put in the Program.cs file.

Can someone post some code that shows how to do this?

Upvotes: 14

Views: 9042

Answers (3)

fziffle
fziffle

Reputation: 3

Solution 4:

When using the new linear application builder for console type application:

var builder = Host.CreateApplicationBuilder(args);
// ...
builder.Services.Configure<HostOptions>(options => 
    options.ShutdownTimeout = TimeSpan.FromSeconds (30));
// ..

Upvotes: 0

Rodion Mostovoi
Rodion Mostovoi

Reputation: 1563

A relevant answer for ASP.NET Core 6+:

Solution 1:

var builder = WebApplication.CreateBuilder(args);
//...
builder.WebHost.UseShutdownTimeout(TimeSpan.FromSeconds(30));
//...
var app = builder.Build();

Solution 2:

var builder = WebApplication.CreateBuilder(args);
//...
builder.Services.Configure<HostOptions>(
     opts => opts.ShutdownTimeout = TimeSpan.FromSeconds(30));
//...
var app = builder.Build();

Solution 3:

var builder = WebApplication.CreateBuilder(args);
//...
builder.Services.PostConfigureAll<HostOptions>(opts => 
    opts.ShutdownTimeout = TimeSpan.FromSeconds(30));
//...
var app = builder.Build();

Solution 3 will be applied after all others.

Upvotes: 7

Jan Hettich
Jan Hettich

Reputation: 9886

OK, I finally figured it out ... Here's an outline the configuration code in my Program.cs Main function, with most of the items elided, to show where the configuration for HostOptins.ShutdownTimeout goes.

public static async Task Main(string[] args)
{
    var host = new HostBuilder()
        .ConfigureHostConfiguration(configHost => {...})
        .ConfigureAppConfiguration((hostContext, configApp) => {...})
        .ConfigureServices((hostContext, services) =>
        {
           services.AddHostedService<ApplicationLifetime>();          
           ...
           services.Configure<HostOptions>(
                opts => opts.ShutdownTimeout = TimeSpan.FromSeconds(10));
        })
        .ConfigureLogging(...)
        .UseConsoleLifetime()
        .Build();

    try
    {
        await host.RunAsync();
    }
    catch(OperationCanceledException)
    {
        ; // suppress
    }
}

To make the this work, here is the StopAsync method in my IHostedService class:

public async Task StopAsync(CancellationToken cancellationToken)
{
    try
    {
        await Task.Delay(Timeout.Infinite, cancellationToken);
    }
    catch(TaskCanceledException)
    {
        _logger.LogDebug("TaskCanceledException in StopAsync");
        // do not rethrow
    }
}

See Graceful shutdown with Generic Host in .NET Core 2.1 for more details about this.

Btw, the catch block in Program.Main is necessary to avoid an unhandled exception, even though I am catching the exception generated by awaiting the cancellation token in StopAsync; because it seems that an unhandled OperationCanceledException is also generated at expiration of the shutdown timeout by the framework-internal version of StopAsync.

Upvotes: 23

Related Questions