How do I stop the self-service Kestrel app?

I have canonical code for self-hosting an asp.net MVP application, inside a task:

            Task hostingtask = Task.Factory.StartNew(() =>
            {
                Console.WriteLine("hosting ffoqsi");
                IWebHost host = new WebHostBuilder()
                    .UseKestrel()
                    .UseContentRoot(Directory.GetCurrentDirectory())
                    .UseIISIntegration()
                    .UseStartup<Startup>()
                    .UseApplicationInsights()
                    .Build();

                host.Run();
            }, canceltoken);

      

When I cancel this task, an ObjectDisposedException is thrown. How can I gracefully close the host?

+6


source to share


2 answers


Found the most obvious way to undo Kestrel. Run has an overload that accepts a cancellation token.

  public static class WebHostExtensions
  {
    /// <summary>
    /// Runs a web application and block the calling thread until host shutdown.
    /// </summary>
    /// <param name="host">The <see cref="T:Microsoft.AspNetCore.Hosting.IWebHost" /> to run.</param>
    public static void Run(this IWebHost host);
    /// <summary>
    /// Runs a web application and block the calling thread until token is triggered or shutdown is triggered.
    /// </summary>
    /// <param name="host">The <see cref="T:Microsoft.AspNetCore.Hosting.IWebHost" /> to run.</param>
    /// <param name="token">The token to trigger shutdown.</param>
    public static void RunAsync(this IWebHost host, CancellationToken token);
  }

      

So by passing the cancellation token



host.Run(ct);

      

solves it.

+10


source


You could send a request to your web server, which would cause the controller action that entered through IApplicationLifetime

would StopApplication()

. Will this work for you?



https://docs.microsoft.com/en-us/aspnet/core/api/microsoft.aspnetcore.hosting.iapplicationlifetime

+5


source







All Articles