Brett Rogers
Brett Rogers

Reputation: 41

Azure App Service WebApp Graceful shutdown/Restart

I have created an ASP.Net Core 2.1 WebApp that has a single HostedService to run a background process, the process can take up to 20 seconds to complete once a cancelation token has been cancelled. This all works fine locally when run on IIS Express - the StopAsync() method is called when the IIS Express site is stopped and waits for the process to complete before the application is terminated.

When I run this app in an Azure App Service it does not shutdown or restart gracefully the StopAsync() is called but the application is killed within a few seconds not allowing the application to shutdown gracefully.

I have tried adding the following in web.config:

<aspNetCore shutdownTimeLimit="90" processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout">

And the following in Program.cs but this had no effect:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseShutdownTimeout(TimeSpan.FromSeconds(90));

Are there any other settings I need to set in an Azure App Service to increase the Shutdown timeout?

Many thanks.

Upvotes: 2

Views: 1829

Answers (1)

Tom Sun
Tom Sun

Reputation: 24569

If we want to gracefully shut down the webapp, we could inject IApplicationLifetime and use the property ApplicationStopping in the Startup.cs

IApplicationLifetime is a new interface in ASP.NET Core under the Microsoft.AspNetCore.Hosting namespace. The interface is designed to give a developer the opportunity to gracefully startup but mostly shutdown the application.

Demo code

public void Configure(IApplicationBuilder app, IHostingEnvironment env,IApplicationLifetime applicationLifetime)
{ 
   ...
   applicationLifetime.ApplicationStopping.Register(OnShutdown);
   ...
}
private void OnShutdown()
{
   //todo
}

Upvotes: 1

Related Questions