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?
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With