How can I know when Kestrel has started listening?

后端 未结 4 1156
旧时难觅i
旧时难觅i 2021-02-15 13:10

I need to notify systemd that my service has started up successfully, and a task it needs to run after startup requires that the server is already listening

4条回答
  •  孤城傲影
    2021-02-15 13:56

    This is what I did to overcome the issue.

    1- I registered ApplicationStopped event. So that it brute force terminates the app by calling Kill() method of the current process.

    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();
     });
    }
    

    See IHostApplicationLifetime docs


    2- Don't forget to use the UseConsoleLifetime() while building the host.

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

    See useconsolelifetime docs

提交回复
热议问题