Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
594 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...