using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
public class MyBackgroundService : BackgroundService
{
private readonly ILogger<MyBackgroundService> _logger;
public MyBackgroundService(ILogger<MyBackgroundService> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("MyBackgroundService is starting.");
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("MyBackgroundService is running at: {time}", DateTimeOffset.Now);
// 模拟一些工作,例如每5秒执行一次任务
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
_logger.LogInformation("MyBackgroundService is stopping.");
}
public override async Task StopAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("MyBackgroundService is stopping.");
// 执行清理工作
await base.StopAsync(stoppingToken);
}
}
继承 BackgroundService
:
MyBackgroundService
类继承自 BackgroundService
,这是一个抽象类,提供了实现后台服务的基础结构。依赖注入:
ILogger<MyBackgroundService>
,用于记录日志信息。ExecuteAsync
方法:
while
循环和 stoppingToken
来确保服务可以在接收到停止请求时优雅地退出。StopAsync
方法:
日志记录:
_logger
记录服务的启动、运行和停止信息,便于调试和监控。这个示例展示了如何创建一个简单的后台服务,并且可以通过依赖注入的方式集成日志记录功能。
上一篇:c# begininvoke
下一篇:c# 序列化
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站