How can I know when Kestrel started listening?

I need to notify systemd

that my service has started successfully and the task it should start after starting requires the server to be listening on the target Unix domain already.

I am using IWebHost::Run

to start the server and this is a blocking call. Also, I cannot find any obvious way to set a delegate or callback event to initialize successfully.

Anyone?

+3


source to share


3 answers


  • In .Net Core 1.x

    can simply start IWebHost.Start()

    and assume that after that the server is initialized (instead Run()

    , which blocks the thread). Check the source.

    var host = new WebHostBuilder()
        .UseKestrel()
        (...)
        .Build();
    
    host.Start();
    
          

  • If you use .NET Core 2.0 Preview 1

    (or later) the source is different , the synchronous method is no longer available so you have to wait IWebHost.StartAsync()

    and assume that everything will be ready after that.



+3


source


You can use 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; }

      



Check out this SO post for a configuration example.

+2


source


This is what I ended up continuing with for now. Seems to work fine:

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...");

      

Then in the Ctrl + C event handler:

private static void OnConsoleCancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
    Log.Debug("Got Ctrl+C from console.");
    CancelTokenSource.Cancel();
}

      

+1


source







All Articles