WynDiesel
WynDiesel

Reputation: 1214

Service worker at runtime

I recently discovered worker services in .net core 3.0, and this sounds perfect for a project that I'm currently working on.

At an interval, my service will collect (from database/file/whatever) tasks that need to be executed. I want to then queue through these tasks, and fire of Tasks for them to be executed on their own.

I cooked up my own home brew solution for this, but, as mentioned above, the worker service sounds like a better tried-and-tested solution to this problem.

I read several tutorials on the topic, and they all use pretty much the same approach; creating a new project from the wizard, and then explaining from there on. From the default template, I understand that this will spin off the worker service :

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

However, I need some way to spin up these workers at run time, and I'm not able to find any guideline on how to do that.

Upvotes: 2

Views: 468

Answers (1)

Fildor
Fildor

Reputation: 16084

I would not take on the hassle to fire up Threads or Workers on demand.

Here's what I'd do:

  1. Have one Worker Service as "Watchdog": Look for new "Tasks". If found, have them enqueued in some sort of Queue.

  2. As you stated: Your Tasks are independent and do not require a "Pipeline". So I'd either start "System.Threading.Tasks.Task"s for each one or maybe have them handled through Parallel

Starting a CPU-bound Task will use a Threadpool Thread, so that should be sufficient for your usecase. If you need more control about the order of execution or degree of parallelism, you may consider DataFlow, although you'll probably have only one Node instead of a Pipeline. But that's up to you.

Upvotes: 1

Related Questions