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?
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.
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://docs.microsoft.com/en-us/aspnet/core/api/microsoft.aspnetcore.hosting.iapplicationlifetime
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With