5

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?

svick
  • 236,525
  • 50
  • 385
  • 514
Jan Hettich
  • 9,146
  • 4
  • 35
  • 34
  • very similar to this: https://stackoverflow.com/questions/47035503/start-multiple-background-threads-inside-self-hosted-asp-net-core-microservice – jazb Oct 16 '18 at 01:04

1 Answers1

5

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".

Martin Ullrich
  • 94,744
  • 25
  • 252
  • 217
  • 2
    That is certainly consistent with what I observed, but the naming (e.g. "BackgroundService") and documentation ("In ASP.NET Core, background tasks can be implemented as hosted services") are a rather misleading in that case. I will see if any other responses come in; otherwise, this will likely become the accepted answer. – Jan Hettich Oct 16 '18 at 13:52
  • 1
    You could also give feedback on the documentation pages when you believe that the documentation is misleading – Martin Ullrich Oct 16 '18 at 14:48