8

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?

citykid
  • 9,916
  • 10
  • 55
  • 91
  • Which platform do you target? When you target linux/macos (not sure later one) you can use linux SIGTERM to send a termination signal to the application – Tseng Mar 31 '17 at 16:09
  • Seems on Windows you can use WM_Close though – Tseng Mar 31 '17 at 16:12
  • I am on Windows, .Net Framework. – citykid Mar 31 '17 at 16:38
  • Did it work? I've never used it, but I know that Kestrel (or the Webhost) reacts on signals sent form the OS for graceful shutdowns. That's what the `IApplicationLifetime` mentioned below is for, to register to the cancellation token and perform cleanup work when the signal was received – Tseng Apr 01 '17 at 10:05
  • thx for your input. i did not yet did into that solution. I expected a simple method call on IWebHorst or so. Currently I accept the exception and just dont care about it. – citykid Apr 02 '17 at 11:07

2 Answers2

12

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.

citykid
  • 9,916
  • 10
  • 55
  • 91
6

You could send a request to your web server that would call a controller action that, via the injected IApplicationLifetime, would call a StopApplication(). Would it work for you?

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

Daboul
  • 2,635
  • 1
  • 16
  • 29
  • hmm, that sounds a bit contrived to me. But IApplicationLifetime looks like the right direction. – citykid Mar 31 '17 at 15:39