Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run multiple BackgroundService parallel in .net core 3.0?

How is it possible to run multiple IHostedServices in parallel?

I use the WorkerService in .Net Core 3.0 and want both services to run parallel. Currently the second service is waiting for the first one to finish. Both services should run endlessly.

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

A service looks like this:

public class ServiceA : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        do
        {
            Console.WriteLine("Sample");
            await Task.Delay(5000, stoppingToken);
        } while (!stoppingToken.IsCancellationRequested);
    }
}

// edit: Very reluctantly I would use a Task.Run(() => method()); method like this. But of course this way always works:

public class ServiceA : BackgroundService
{
    public override Task StartAsync(CancellationToken cancellationToken)
    {
        Task.Factory.StartNew(() => ExecuteAsync(cancellationToken), cancellationToken);
        return Task.CompletedTask;
    }
}
like image 391
cSteusloff Avatar asked Oct 07 '19 10:10

cSteusloff


People also ask

How to implement background task in ASP NET Core?

For the implementation of the background task, we dont need any Nuget packages or anything et. It is in core ASP.NET infrastructure itself. We know that the background tasks can be implemented in main two ways in ASP.NET core using BackgroundService Class and IHostedService.

How to configure multiple services in ASP NET Core?

You can configure various services just like you would in ASP.NET Core; Dependency Injection via AddSingleton() or AddTransient(); logging via AddLogging(); or configuration via AddOptions(). The main difference is in ConfigureServices(), where the new extension method, AddHostedService < T > where T : class, IHostedService is called.

What is the difference between monitorloop and backgroundprocessing?

The BackgroundProcessing method returns a Task, which is awaited in ExecuteAsync. Background tasks in the queue are dequeued and executed in BackgroundProcessing. Work items are awaited before the service stops in StopAsync. A MonitorLoop service handles enqueuing tasks for the hosted service whenever the w key is selected on an input device:

How to create a background service from the web API?

In this article, I'm going to explain how to create a background service and invoke that service from the .NET Core web API. Let's go step by step. In Visual Studio, click on File, go to New, and select the appropriate project template. Click on "Next" and enter the project name and create. Step 2 - Create a class library project.


1 Answers

I asked myself a similar question and made some search but couldn't find a good answer. I solved the issue running every background service in Task.Run with a cancellation token from BackgroundService.ExecuteAsync() I have 2 services like you.

public class BackgroundService1: BackgroundService
{
    public BackgroundService1()
    {
    }
    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        Task.Run(async () =>
        {
            await DoWork(stoppingToken);
        }, stoppingToken);
        return Task.CompletedTask;
    }
}

//Second service is just like the first one:

public class BackgroundService2: BackgroundService
{
    public BackgroundService2()
    {
    }
    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        Task.Run(async () =>
        {
            await DoWork(stoppingToken);
        }, stoppingToken);
        return Task.CompletedTask;
    }
}

and register them in Program.cs

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<BackgroundService1>();
                services.AddHostedService<BackgroundService2>();
            })
            .UseWindowsService()
like image 94
ibrahimozgon Avatar answered Sep 17 '22 14:09

ibrahimozgon