asp.net-coreasp.net-core-mvckestrel-http-server

How to stop a self hosted Kestrel application?


I have the canonical code to self host an asp.net mvc 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 throws. How can I gracefully shut down the host?


Solution

  • Found the most obvious way to cancel Kestrel. Run has an overload accepting 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 passing the cancellation token to

    host.Run(ct);
    

    solves it.