private static async Task WaitForTokenShutdownAsync(this IAppHost host, CancellationToken token) { var applicationLifetime = host.Services.GetService <IApplicationLifetime>(); token.Register(state => { ((IApplicationLifetime)state).StopApplication(); }, applicationLifetime); var waitForStop = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously); applicationLifetime.ApplicationStopping.Register(obj => { var tcs = (TaskCompletionSource <object>)obj; tcs.TrySetResult(null); }, waitForStop); await waitForStop.Task; // WebHost will use its default ShutdownTimeout if none is specified. await host.StopAsync(); }