?.NET 通用主机负责应用启动和生存期管理,主机是封装应用资源和生存期功能的对象,通用主机可用于其他类型的 .NET 应用程序,如控制台应用;.NET 通用主机基于类库Microsoft.Extensions.Hosting?来实现,本文记录如何使用.NET 辅助角色服务模板来创建通用主机。
以下示例是注册?IHostApplicationLifetime
?事件的?IHostedService
?实现
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
public sealed class ExampleHostedService : IHostedService
{
private readonly ILogger _logger;
private IHostApplicationLifetime _applicationLifetime;
public ExampleHostedService(
ILogger<ExampleHostedService> logger,
IHostApplicationLifetime appLifetime)
{
_logger = logger;
appLifetime.ApplicationStarted.Register(OnStarted);
appLifetime.ApplicationStopping.Register(OnStopping);
appLifetime.ApplicationStopped.Register(OnStopped);
_applicationLifetime = appLifetime;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("1. StartAsync has been called.");
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("4. StopAsync has been called.");
return Task.CompletedTask;
}
private async void OnStarted()
{
_logger.LogInformation("2. OnStarted has been called.");
var count = 0;
var task = Task.Run(() =>
{
while (true)
{
count++;
Console.WriteLine("running...");
Thread.Sleep(1000);
if (count == 5)
{
_applicationLifetime.StopApplication();
}
}
});
}
private void OnStopping()
{
_logger.LogInformation("3. OnStopping has been called.");
}
private void OnStopped()
{
_logger.LogInformation("5. OnStopped has been called.");
}
}
修改辅助角色服务模板以添加?ExampleHostedService
?实现
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
builder.Services.AddHostedService<ExampleHostedService>();
IHost host = builder.Build();
host.Run();
Environment.Exit(0);
运行示例后可以用Ctrl+C或等待5秒后退出主机应用的执行流程,调用结果如下: