8

我需要通知systemd我的服务已成功启动,并且它需要在启动后运行的任务要求服务器已经在侦听目标 Unix 域套接字。

IWebHost::Run用来启动服务器,这是一个阻塞调用。此外,我找不到任何明显的方法来设置成功初始化的委托或回调事件。

任何人?

4

4 回答 4

4

您可以使用Microsoft.AspNetCore.Hosting.IApplicationLifetime

/// <summary>
/// Triggered when the application host has fully started and is about to wait
/// for a graceful shutdown.
/// </summary>
CancellationToken ApplicationStarted { get; }

查看此SO 帖子以获取配置示例。

于 2017-06-21T05:57:24.607 回答
3
  • .Net Core 1.x运行IWebHost.Start()并假设服务器随后被初始化是安全的(而不是阻塞Run()线程)。检查来源

    var host = new WebHostBuilder()
        .UseKestrel()
        (...)
        .Build();
    
    host.Start();
    
  • 如果您正在使用.NET Core 2.0 Preview 1(或更高版本),则源不同,同步方法不再可用,因此您应该等待IWebHost.StartAsync()并假设一切都准备就绪。

于 2017-06-21T04:16:20.177 回答
1

这就是我最终的结果,现在。似乎工作正常:

host.Start();

Log.Information("Press Ctrl+C to shut down...");
Console.CancelKeyPress += OnConsoleCancelKeyPress;

var waitHandles = new WaitHandle[] {
    CancelTokenSource.Token.WaitHandle
};

WaitHandle.WaitAll(waitHandles);
Log.Information("Shutting down...");

然后,在 Ctrl+C 事件处理程序中:

private static void OnConsoleCancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
    Log.Debug("Got Ctrl+C from console.");
    CancelTokenSource.Cancel();
}
于 2017-06-20T22:24:10.767 回答
0

这就是我为克服这个问题所做的。

1-我注册ApplicationStopped了活动。Kill()这样它就会通过调用当前进程的方法来蛮力终止应用程序。

public void Configure(IHostApplicationLifetime appLifetime) {
 appLifetime.ApplicationStarted.Register(() => {
  Console.WriteLine("Press Ctrl+C to shut down.");
 });

 appLifetime.ApplicationStopped.Register(() => {
  Console.WriteLine("Terminating application...");
  System.Diagnostics.Process.GetCurrentProcess().Kill();
 });
}

请参阅 IHostApplicationLifetime 文档


2-不要忘记UseConsoleLifetime()在构建主机时使用。

Host.CreateDefaultBuilder(args).UseConsoleLifetime(opts => opts.SuppressStatusMessages = true);

请参阅 useconsolelifetime 文档

于 2019-12-02T10:59:40.660 回答