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
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…