假设以下使用通用主机的 .NET Core 2.2 控制台应用程序:
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;
}
}
}
当您运行它时,将输出以下内容:
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
正如你所看到的,SimpleHostedService.StopAsync被调用了两次。为什么?
这是预期的吗?我错过了什么吗?IHostedService.StopAsync还有另一种方法可以停止只被调用一次的主机吗?
噜噜哒
相关分类