Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BackgroundService tasks not running on separate threads in .NET Core Generic Host

The new .NET Core "Generic Host" seemed like a good choice for implementing a console application that runs several concurent tasks. Rather than explicitly creating and running the tasks, I thought I could define them as services using IHostedService (or BackgroundService). However, the Generic Host is executing all my so-called "background tasks" on the same thread. Is this the intended behavior?

public static async Task Main(string[] args)
    {
        var host = new HostBuilder()
        .ConfigureHostConfiguration(...)
        .ConfigureAppConfiguration(...)
        .ConfigureServices((hostContext, services) =>
        {
            services.AddLogging();
            services.AddHostedService<Service1>();
            services.AddHostedService<Service2>();
            services.AddHostedService<Service3>();
        })
        .ConfigureLogging(...)
        .UseConsoleLifetime()
        .Build();

        await host.RunAsync();
    }

The Generic Host runs all three of my "background" services on the same thread. Thread.CurrentThread.ManagedThreadId was found to equal 1 on the Main thread and within the StartAsync or ExecuteAsync methods of each of the "background" services. Is there a way to ensure that the services run on separate threads?

like image 452
Jan Hettich Avatar asked Oct 16 '18 00:10

Jan Hettich


1 Answers

The IHostedService interface only gives you hooks for starting and stopping your work. you are responsible for implementing threading, background events etc. yourself based on what your service does. You could set up a timer that executes events asynchronously or set up a running background thread etc.

The generic host does not imply a threading or execution model for your "services".

like image 101
Martin Ullrich Avatar answered Nov 09 '22 22:11

Martin Ullrich