ChrisCa
ChrisCa

Reputation: 11046

Multiple Hosted Services in Dotnet Core Windows Service

I have a windows service for netcore 2.0 which is based on this example: https://www.stevejgordon.co.uk/running-net-core-generic-host-applications-as-a-windows-service

The main hosted service in my case is subscribed to a message queue and processes the messages sequentially (an event is raised by the queue api each time a new message appears). If any messages cannot be processed they are moved to a different queue to be retried (x number of times, with exponential back-off). And so this needs to be done on a separate thread so as not to cause delays on the processing of the main queue

Is it ok to configure 2 HostedServices:

var builder = new HostBuilder()
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<MyMsgProcessingService>();
                services.AddHostedService<MyRetryService>();
            });

This does start and it does hit the StartAsync method (on the IHostedService interface) of each service

Or are you only allowed to have (is a good idea to have) one IHostedService implementation?

If two is OK, will the work on the slow service hold up the wok on the main service?

If only one, is it best to just spin up another thread to do the work for the retry queue? And how would I ensure that the new thread lives for the whole time the service is running? a while loop seems inappropriate as I'm just waiting for an event to be raised

e.g.

public Task StartAsync(CancellationToken cancellationToken)
{
    Task t = Task.Run(() => ProcessRetrys(), cancellationToken);

Upvotes: 9

Views: 13438

Answers (1)

cassandrad
cassandrad

Reputation: 3536

Or are you only allowed to have (is a good idea to have) one IHostedService implementation?

You can have as many as you want. As long as you are okay with the fact that if the process goes down, everything in it (all of services) are too go down.

Second thing to consider is thread pool. Thread pool is common for all the services, so if one of them is hungry for threads, others could be impacted.

If two is OK, will the work on the slow service hold up the wok on the main service?

Depends on if one service waits data from another. And on type of communication between them. If it's synchronous, then the slowest thread will be the bottleneck.

And how would I ensure that the new thread lives for the whole time the service is running?

Create a foreground thread. About. How to configure. But you have to be careful and terminate such thread graceful when the app shuts down, handling it in StopAsync method invocation.

a while loop seems inappropriate as I'm just waiting for an event to be raised

Use non-blocking queues to communicate between services. I can't give you a link on a specific implementation, because there are plenty of them, but you can start another question to help you find an appropriate one.

Upvotes: 8

Related Questions