asp.net core mvc 3.1 中的后台任务 [英] Background task in asp.net core mvc 3.1

查看:57
本文介绍了asp.net core mvc 3.1 中的后台任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 asp.net core mvc 应用程序中运行后台任务.

I want to run a background task in an asp.net core mvc application.

这是我所做的:

在 Startup.cs 中:

in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
   ...
   services.AddHostedService<MyTask>();
}

在 MyTask.cs 中:

in MyTask.cs:

public class MyTask: BackgroundService
{
   ...
   public override async Task StartAsync(CancellationToken cancellationToken)
   {
      _logger.LogInformation("StartAsync");
   }

   public override async Task StopAsync(CancellationToken cancellationToken)
   {
      _logger.LogInformation("StopAsync");
   }

   ...
}

这是我注意到的:- 当我在 IIS 上部署我的网站时,我需要点击一个页面才能启动服务- 我注意到如果我什么都不做,就会调用 Stop.

Here what i've notice: - When i am deploying my website on IIS, i need to hit a page in order to start service - I have notice the Stop is called if i do nothing.

我的问题是:如何使我的应用程序保持活动状态?我需要每分钟运行一次任务...

My question is: How to keep alive my application ? I need to run task each minute...

谢谢

推荐答案

在 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

这篇关于asp.net core mvc 3.1 中的后台任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆