I am totally new to ASP.NET Core so I am probably missing something by 50 miles because I've spent 3 hours on this to no avail.
I've made a Web App from within VS 2017, hosted by Kestrel which runs under IIS Express (which is all default when you make a new web app). When I press F5 the app fires up, my Chrome browser opens up and I see the 'hello world'-esque output. When I close this browser window the app terminates.
Now, I need some tasks going on in the background and I need these tasks to have cleanup logic - I found that IHostedService
allows me to do this.
The documentation states:
When you register an IHostedService, .NET Core will call the StartAsync() and StopAsync() methods of your IHostedService type during application start and stop respectively.
I have done:
public void ConfigureServices(IServiceCollection services)
{
services.AddHostedService<MyBackgroundService>();
}
And the service starts as expected, everything is fine. Extremely simple stuff. But it never stops, not gracefully at least.
When I close that auto-started browser window, my app closes along with it but this method in my IHostedService
service:
public Task StopAsync(CancellationToken cancellationToken)
{
...
}
Is never called.
I have tried the example provided in documentation and it exhibits the same issue - the cleanup is never done when I try it in VS.
I have noticed a peculiar information from an output channel called "ASP.NET Core Web Server":
BackgroundTasksSample> Application started. Press Ctrl+C to shut down.
It's obviously some redirection from the console as this app appears to be a console app in the first place. So I wonder if VS is, by seemingly hiding the console from me, preventing me from performing the graceful shut down of my app?
I also noticed a little IIS Express tray icon which lists any apps I've ran and it has a Stop button which doesn't seem to do anything. I assume IIS Express is here simply acting as some kind of a proxy.
I am dumbfounded, especially since I seem to be the only one having this problem.
How do I properly terminate my Web App?