Asp.net-Core
如何停止自託管 Kestrel 應用程序?
我有規范程式碼可以在任務中自行託管 asp.net mvc 應用程序:
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);當我取消此任務時,會拋出 ObjectDisposedException。如何優雅地關閉主機?
找到取消 Kestrel 的最明顯方法。執行有一個接受取消令牌的重載。
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); }所以將取消令牌傳遞給
host.Run(ct);解決它。