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?