如何使用HostBuilder通用主机ref StopAsync OperationCanceledException

时间:2018-10-20 22:46:51

标签: c# multithreading asp.net-core-2.1

查看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);
        }

    }

}

1 个答案:

答案 0 :(得分:1)

感谢这篇关于SuppressStatusMessages

的帖子,我收集了答案
.ConfigureServices((hostContext, services) =>
    {
    services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(90));