Given the following .NET Core 2.2 console application that uses generic host:
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace SimpleGenericHost
{
class SimpleHostedService : IHostedService
{
public Task StartAsync(CancellationToken cancellationToken)
{
Console.WriteLine("Service started");
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
Console.WriteLine("Service stopped");
return Task.CompletedTask;
}
}
class Program
{
static async Task Main(string[] args)
{
var host = new HostBuilder()
.ConfigureServices(services =>
{
services.AddHostedService<SimpleHostedService>();
})
.Build();
var runTask = host.RunAsync();
await Task.Delay(5000);
await host.StopAsync();
await runTask;
}
}
}
When you run it, the following is output:
Service started
Application started. Press Ctrl+C to shut down.
Hosting environment: Production
Content root path: C:\projects\ConsoleApps\SimpleGenericHost\bin\Debug\netcoreapp2.2\
Service stopped
Service stopped
As you can see SimpleHostedService.StopAsync
is called twice. Why?
Is this expected? am I missing something? Is there another way to stop the host that IHostedService.StopAsync
is called just once?