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

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

问题描述

我想在asp.net核心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上部署网站时,我需要点击一个页面才能启动服务 -我注意到,如果我什么都不做,则会叫停.

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天全站免登陆