且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

asp.net core mvc 3.1 中的后台任务

更新时间:2023-02-15 13:04:57

在 ASP.NET Core 中,后台任务可以作为托管服务来实现.托管服务是一个具有后台任务逻辑的类,它实现了 IHostedService 接口.

In ASP.NET Core, background tasks can be implemented as hosted services. A hosted service is a class with background task logic that implements the IHostedService interface.

定时后台任务使用 System.Threading.Timer 类.计时器触发任务的 DoWork 方法.计时器在 StopAsync 上被禁用,当服务容器在 Dispose 上被释放时被释放:

A timed background task makes use of the System.Threading.Timer class. The timer triggers the task's DoWork method. The timer is disabled on StopAsync and disposed when the service container is disposed on Dispose:

public class TimedHostedService : IHostedService, IDisposable
{
    private int executionCount = 0;
    private readonly ILogger<TimedHostedService> _logger;
    private Timer _timer;

    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(5));

        return Task.CompletedTask;
    }

    private void DoWork(object state)
    {
        var count = Interlocked.Increment(ref executionCount);

        _logger.LogInformation(
            "Timed Hosted Service is working. Count: {Count}", count);
    }

    public Task StopAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Timed Hosted Service is stopping.");

        _timer?.Change(Timeout.Infinite, 0);

        return Task.CompletedTask;
    }

    public void Dispose()
    {
        _timer?.Dispose();
    }
}

Timer 不会等待 DoWork 的先前执行完成,因此所示方法可能不适用于所有场景.Interlocked.Increment 用于将执行计数器递增为原子操作,确保多个线程不会同时更新 executionCount.

The Timer doesn't wait for previous executions of DoWork to finish, so the approach shown might not be suitable for every scenario. Interlocked.Increment is used to increment the execution counter as an atomic operation, which ensures that multiple threads don't update executionCount concurrently.

使用 AddHostedService 扩展方法在 IHostBuilder.ConfigureServices (Program.cs) 中注册服务:

The service is registered in IHostBuilder.ConfigureServices (Program.cs) with the AddHostedService extension method:

    services.AddHostedService<TimedHostedService>();

要查看更多详细信息,请单击以下链接:微软文档

To see more detail click below link : Microsoft Documentation