且构网

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

ASP.NET Core MVC 3.1中的后台任务

更新时间:2023-02-15 13:00:22

在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