Ehsan Ghanbari

Experience, DotNet, Solutions

Multiple workers in asp.net core

In asp.net core project templates, you can find something name Worker. It’s a service-based project which has the capability of being converted to windows service. After creating the project, you can see the following piece of code as worker service:

 

  public class Worker : BackgroundService

    {

        private readonly ILogger<Worker> _logger;

 

        public Worker(ILogger<Worker> logger)

        {

            _logger = logger;

        }

 

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)

        {

            while (!stoppingToken.IsCancellationRequested)

            {

                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);

                await Task.Delay(1000, stoppingToken);

            }

        }

    }

 

It's being hosted in Program  class:

 

 public class Program

    {

        public static void Main(string[] args)

        {

            CreateHostBuilder(args).Build().Run();

        }

 

        public static IHostBuilder CreateHostBuilder(string[] args) =>

            Host.CreateDefaultBuilder(args)

                .ConfigureServices((hostContext, services) =>

                {

                    services.AddHostedService<Worker>();

                });

    }

 

You can have multiple workers in ExecuteAsync by changing a bit:

 

 public class Worker : BackgroundService

    {

        private readonly ILogger<Worker> _logger;

 

        public Worker(ILogger<Worker> logger)

        {

            _logger = logger;

        }

       

        protected override Task ExecuteAsync(CancellationToken stoppingToken)

        {

            return Task.Factory.StartNew(async () =>

            {

                while (!stoppingToken.IsCancellationRequested)

                {

                    var workers = new List<Task>

                    {

                        RunWorker1(stoppingToken),

                        RunWorker2(stoppingToken)

                    };

                    await Task.WhenAll(workers.ToArray());

                }

            }, stoppingToken);

        }

 

        private async Task RunWorker1(CancellationToken stoppingToken)

        {

            while (!stoppingToken.IsCancellationRequested)

            {

                _logger.LogInformation("Worker1 running at: {time}", DateTimeOffset.Now);

                await Task.Delay(1000, stoppingToken);

            }

        }

 

        private async Task RunWorker2(CancellationToken stoppingToken)

        {

            while (!stoppingToken.IsCancellationRequested)

            {

                _logger.LogInformation("Worker2 running at: {time}", DateTimeOffset.Now);

                await Task.Delay(1000, stoppingToken);

            }

        }

    }

 

About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
Peridic pattern
How to query over Icollection<> of a type with linq
How to use PagedList In asp.net MVC
Domain driven design VS model driven architecture
What's the DDD-lite?
Using Generic type for type casting in F#
comments powered by Disqus