11

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?

Jan Hettich
  • 9,146
  • 4
  • 35
  • 34
  • Are you using ASP.NET Core? If so, please edit your question and add the `asp.net-core` tag to it, so that is easier for users to find it. Also, if that's the case, maybe you're looking for the [UseShutdownTimeout()](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.hosting.hostingabstractionswebhostbuilderextensions.useshutdowntimeout) extension method, which you can call in your web host builder object to configure a TimeSpan for the shutdown time. – vinicius.ras Oct 21 '18 at 12:08
  • No, I am using the Generic Host. I updated the question to make that clearer. The `HostOptions` class defines a property `public TimeSpan ShutdownTimeout { get; set; } = TimeSpan.FromSeconds(5);`, but it is not clear to me how to apply it in the `HostBuilder` configuration. – Jan Hettich Oct 21 '18 at 15:24
  • I should further clarify that I am using .NET Core 2.1.1. – Jan Hettich Oct 21 '18 at 16:20

2 Answers2

20

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.

Igor
  • 349
  • 1
  • 6
Jan Hettich
  • 9,146
  • 4
  • 35
  • 34
  • 2
    I may be wrong or it may not have been previously possible but why not just use `services.Configure(x => x.ShutdownTimeout = TimeSpan.FromSeconds(10))`? – Ray Mar 17 '20 at 23:06
4

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.

Rodion Mostovoi
  • 1,205
  • 12
  • 16