Worker Service in .Net Core 3.0

What is a Worker Service, what is solves?

Sometimes our business scenarios need long-running tasks that run in the background, to watch something or compute something.

This kind of scenario was impossible before .Net Core 2.1. A lot of functionalities were ‘ported’ or re-written from the old version, but this wasn’t included.

In the old .Net full-framework, we use to implement long-running tasks as Windows services. We delivered them in production not without a lot of hassle.

When .Net Core appeared, it promised to be not only faster, smaller, performant but also cross-platform.

It opened a whole new world to .Net developers, it allowed us to change hosting environments as we pleased but it didn’t provide us the whole ecosystem that we had in .Net full-framework.

Building background-services was impossible until a later version of .Net.

With .Net core 2.1 release, there was an option to have a self-hosting service inside your web app by implementing IHostedService interface. Later on, they introduced the concept of BackgroundService that you could customize.

Worker Services become a first-class citizen in .Net Core 3.0. Visual Studio 2019 has a template for it. It was bringing back the concept of ‘service’ as we used to know in .Net full-framework.

VIsual Studio 2019 Project template
Visual Studio 2019 Project template

The generated project is composed of 2 classes and an appsettings.json which is more than enough to get started.

Working With Worker Services
The generated project

Worker Service Implementation

At its basis, it’s nothing more than a small and smart console app that has a built-in DI container.

public static IHostBuilder CreateHostBuilder(string[] args=>
         Host.CreateDefaultBuilder(args)
             .ConfigureServices((hostContextservices=>
             {
                 services.AddHostedService<Worker>();
             });

This will allow you to register all the dependencies (repositories, business services, external libs) that will be used in your Worker, just as you do in Web API or MVC.

The base class BackgroundService – was built to provide a way of running long-running tasks in the background under .Net Core. A Worker is exactly that – a long-running, background task.

The Worker.cs class is everything you need to implement your functionality. You can control what to run and when to run in ExecuteAsync method.

public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;
 
        public Worker(ILogger<Workerlogger)
        {
            _logger = logger;
        }
 
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Worker running at: {time}"DateTimeOffset.Now);
                await Task.Delay(1000stoppingToken);
            }
        }
    }

Having the new Worker Service in .Net Core will allow us to cover different business scenarios. Polling a service, running a specific task at a specific time will be very easy.

Leave a Comment

Your email address will not be published. Required fields are marked *