查看source code,StopAsync的默认超时为5秒。 WebHostBuilder提供了扩展方法 UseShutdownTimeout 用于轻松设置。但是 HostBuilder没有此类等效项。
我知道我可能想要超过5秒钟的超时来滥用HostBuilder的意图,但这是一个用于管理一系列相互依赖的作业的好框架。
我非常感谢有关如何使用HostBuilder进行操作的指南,以及UseShutdownTimeout对WebHostBuilder的作用,同时仍在使用正式的NuGet软件包。我看了一下扩展HostingAbstractionsHostBuilderExtensions,但这是一个静态类...
下面的示例控制台应用程序,用于触发StopAsync OperationCanceledException事件。在10秒钟之前,只需按Ctrl + C。
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace StackOverflow_GenericHost_StopAsync
{
class Program
{
static async Task Main(string[] args)
{
var host = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services.AddSingleton<IHostedService, MustRunToCompletionService>();
})
.Build();
await host.StartAsync();
try
{
await host.WaitForShutdownAsync();
}
catch (OperationCanceledException ex)
{
// We have completed a controlled shutdown but the Exception is ugly
Console.WriteLine(ex);
Console.ReadKey();
}
// just hangs if we don't
host.Dispose();
}
}
class MustRunToCompletionService : IHostedService
{
private Task _longRunningTask;
private async Task MustCompleteProcess()
{
// simulate long running job
Thread.Sleep(15000);
}
public Task StartAsync(CancellationToken cancellationToken)
{
_longRunningTask = Task.Run(MustCompleteProcess);
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
// ignore cancellationToken, I really need this to run to completion
return Task.WhenAll(_longRunningTask);
}
}
}
答案 0 :(得分:1)
感谢这篇关于SuppressStatusMessages
的帖子,我收集了答案.ConfigureServices((hostContext, services) =>
{
services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(90));