1.1、创建后台任务,需要继承BackgroundService,StartAsync可以不用实现,代码如下:
public class TestWorker: BackgroundService
{
private readonly ILogger<TestWorker> _logger;
public TestWorker(IServiceProvider services,
ILogger<TestWorker> logger)
{
Services = services;
_logger = logger;
}
public IServiceProvider Services { get; }
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation(
"Consume Scoped Service Hosted Service running.");
await DoWork(stoppingToken);
}
private async Task DoWork(CancellationToken stoppingToken)
{
Console.WriteLine("DoWork开始工作");
int js = 0;
while (!stoppingToken.IsCancellationRequested)
{
js++;
Console.WriteLine($"计数执行器:{js}");
await Task.Delay(1000, stoppingToken);
}
}
//public override async Task StartAsync(CancellationToken cancellationToken)
//{
// int js = 1000;
// while (!cancellationToken.IsCancellationRequested)
// {
// js++;
// Console.WriteLine($"计数执行器:{js}");
// await Task.Delay(1000,cancellationToken);
// }
//}
public override async Task StopAsync(CancellationToken stoppingToken)
{
_logger.LogInformation(
"后台服务结束");
await base.StopAsync(stoppingToken);
}
}
1.2、调用方法
builder.Services.AddHostedService<TestWorker>();
1.3、执行结果
2.2、定时任务的创建,需要实现IHostedService, IDisposable两个接口,代码如下:
public class TimedHostedService : IHostedService, IDisposable
{
private int executionCount = 0;
private int executionCount2 = 0;
private readonly ILogger<TimedHostedService> _logger;
private Timer _timer = null!;
private Timer _timer2=null!;
public TimedHostedService(ILogger<TimedHostedService> logger)
{
_logger = logger;
}
public Task StartAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Timed Hosted Service running.");
_timer = new Timer(DoWork, null, TimeSpan.Zero,
TimeSpan.FromSeconds(1));
_timer2 = new Timer(DoWork2, null, TimeSpan.Zero,
TimeSpan.FromSeconds(10));
return Task.CompletedTask;
}
private void DoWork(object? state)
{
var count = Interlocked.Increment(ref executionCount);
Console.WriteLine($"1号后台计数器{count}");
}
private void DoWork2(object? state)
{
var count = Interlocked.Increment(ref executionCount2);
Console.WriteLine($"2号后台计数器{count}");
}
public Task StopAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Timed Hosted Service is stopping.");
_timer?.Change(Timeout.Infinite, 0);
_timer2?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
_timer2.Dispose();
}
}
2.2、调用方法
builder.Services.AddHostedService<TimedHostedService>();
2.3、执行结果
应用场景说明
后台任务执行并不理解,因为会被阻塞,所以然另不需要阻塞的话,用定时后台任务比较合适;另外,后台任务被阻塞的情况是否有办法解决呢?