安装依赖包
Install-Package Microsoft.Extensions.Hosting
自定义Host服务
internal class HostedService : IHostedService
{
/// <summary>
/// 主机启动时调用
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public Task StartAsync(CancellationToken cancellationToken)
{
LogInfo.Info("Host Start!");
return Task.Run(() =>
{
//模拟定时任务
while (true)
{
LogInfo.Info("Host运行中..");
Thread.Sleep(1000);
}
});
}
/// <summary>
/// 主机停止时调用
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public Task StopAsync(CancellationToken cancellationToken)
{
LogInfo.Info("Host Stop!");
return Task.CompletedTask;
}
}
注册Host服务并启动主机
static async Task Main(string[] args)
{
var hostBuilder = new HostBuilder().ConfigureServices(serviceCollection =>
{
//注册Host服务接口
serviceCollection.AddHostedService<HostedService>();
});
await hostBuilder.RunConsoleAsync();
}
评论区