.NET Core 3.1 Windows服务启动超时

iezvtpos  于 2023-03-31  发布在  .NET
关注(0)|答案(1)|浏览(241)

我们有一个.NET Core 3.1 Windows服务,偶尔会在启动时超时。该服务达到30秒的Windows服务默认超时,并且不再启动,而是手动启动。
这是创建和启动服务的代码:

public static void Main(string[] args)
    {
        var logger = LogHelper.GetLogger();

        try
        {
            logger.Info($"Starting {Assembly.GetExecutingAssembly().FullName} Branch: {ThisAssembly.Git.Branch} Commit: {ThisAssembly.Git.Commit}");

            var host = Host.CreateDefaultBuilder(args)
                        .UseContentRoot(Directory.GetCurrentDirectory())
                        .ConfigureWebHostDefaults(webBuilder =>
                        {
                            webBuilder
                            //.UseIISIntegration()
                            .UseStartup<Startup>();
                        })
                        .ConfigureLogging(logging =>
                        {
                            logging.ClearProviders();
                            logging.SetMinimumLevel(LogLevel.Trace);
                        })
                        .UseNLog()
                        .UseWindowsService()
                        .Build();

            host.Run();
        }
        catch (Exception exception)
        {
            //NLog: catch setup errors
            logger.Error(exception, "Stopped program because of exception");
            throw;
        }
        finally
        {
            // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
            NLog.LogManager.Shutdown();
        }
    }

显然,在大多数安装过程中,服务都能在合理的时间内正确启动。问题主要发生在“性能不佳的服务器”重新启动时。
有人知道吗?
谢谢。

368yc8dk

368yc8dk1#

您可以尝试从WindowsServiceLifetime派生,该WindowsServiceLifetime派生自具有受保护方法RequestAdditionalTime的老朋友ServiceBase
也许是这样的:

builder.UseWindowsService(o => o.ServiceName = sn);
builder.Services.AddSingleton<IHostLifetime, AdditionalTimeLifetime>();
class AdditionalTimeLifetime : WindowsServiceLifetime
    {
        protected override void OnStart(string[] args)
        {
            base.OnStart(args);
    
            RequestAdditionalTime(TimeSpan.FromSeconds(60));
        }
    }

另请参阅:https://github.com/dotnet/runtime/issues/75276
标签:https://learn.microsoft.com/en-us/dotnet/core/extensions/windows-service

相关问题