实现原理 : 使用 IHostedService 和 BackgroundService 基类
官方文档
创建控制台应用
class Program
{
static void Main(string[] args)
{
Host.CreateDefaultBuilder().ConfigureServices((builder, services) =>
{
var config = builder.Configuration;
services.Configure<MyOptions>(options => config.Bind(options));
services.AddSingleton<MyDemo>();
services.AddHostedService<Worker>(); //参考下方的两个Worker例子
})
.ConfigureHostConfiguration(buider =>
{
buider.AddJsonFile("./appsettings.json");//如果你的worker类继承自BackgroundService则不需要该操作
})
.Build()
.Run();
}
}
worker类继承自IHostedService
- 最原始的接口,自己将作为builder (例如:手动设置appsettings.json)
public class Worker1 : IHostedService //这是最原始的接口
{
private readonly ILogger _logger;
private readonly IHostApplicationLifetime _lifetime;
public Worker1(ILogger<Worker1> logger,
IHostApplicationLifetime lifetime)
{
_logger = logger;
_lifetime = lifetime;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("PHP是世界上最好的语言");
_lifetime.StopApplication();
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
worker类继承自BackgroundService
public class Worker2 : BackgroundService //这是实现部分功能的抽象类
{
private readonly ILogger _logger;
private readonly IHostApplicationLifetime _lifetime;
public Worker2(ILogger<Worker2> logger,
IHostApplicationLifetime lifetime)
{
_logger = logger;
_lifetime = lifetime;
}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("PHP是世界上最好的语言");
_lifetime.StopApplication();
return Task.CompletedTask;
}
}