Use Worker Service in .NET Core in (a supporting role service)

 

What is Worker Service (auxiliary role service)?

.NET Core 3.0 added a new project template Worker Service, and you can write long-running background service, and can easily be deployed into service windows or linux daemons.

If you are installing vs2019 is the Chinese version, Worker Service project name becomes a secondary role service.

IHostedService interface methods:

StartAsync (CancellationToken) - contains the logic to start background tasks.

StopAsync (CancellationToken) - triggered when the host normally closed.

About BackgroundService

BackgroundService is a base class implementation of the long-running IHostedService.

Tutorial

Case - timed background tasks

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Demo_WorkerService_0320
{
    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, DateTime.Now.Ticks, TimeSpan.Zero, TimeSpan.FromSeconds(2));
            return Task.CompletedTask;
        }

        private void DoWork(object state)
        {
            var count = Interlocked.Increment(ref executionCount);
            _logger.LogInformation($" *** Index = {count}, task start... *** ");
            Thread.Sleep(5 * 1000);
            _logger.LogInformation($" *** Index = {count}, task complete ***");
        }

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

Preview

Reference material

Background tasks using managed service implementation in ASP.NET Core in
https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-3.1&tabs=visual-studio

The use of .NET Core Worker Service, to create a windows service or linux daemons
https://www.cnblogs.com/OpenCoder/p/12191164.html

Guess you like

Origin www.cnblogs.com/jinzesudawei/p/12535904.html