0

I have an application which acts as a gateway has two processes in it and they are continuously processing a stream of events. Both of the Processes have start and stop methods on them. They talk to each other via an event queue.

public class ServiceComposite: IHostedService
{
    public ServiceComposite(IServiceA serviceA, IServiceB serviceB)
    {
        this.serviceA = serviceA;
        this.serviceB = serviceB;
    }

    public Task StartAsync(CancellationToken token)
    {
        return Task.Run(() => 
        {
            Console.Writeline("Starting services");
            serviceA.Start();
            serviceB.Start();
        }, token);
    }

    public Task StopAsync(CancellationToken token)
    {
        return Task.Run(() => 
        {
            Console.Writeline("Stopping services");
            serviceA.Stop();
            serviceB.Stop();
        }, token);
    }
}

At first I wanted to create an interface with a start and stop method on it because then I could just inject an IEnumerable and loop through it to start and stop. But then I saw that IHostedService has a very similar interface with StartAsync and StopAsync.

What are the pros and cons of keeping them as I originally had it, i.e. a single IHostedService implementation which control both processes and the pros and cons of turning my process into an IHostService and register both with

services.AddHostedService<ServiceA>();
services.AddHostedService<ServiceB>();
Joelius
  • 3,839
  • 1
  • 16
  • 36
uriDium
  • 13,110
  • 20
  • 78
  • 138
  • They'll work exactly the same. It's completely up to you but personally, I'd go with separating them since you could potentially use generics if your `IServiceA` and `IServiceB` have a common interface which you can target. Then you could even discover and register all those services automatically. – Joelius Nov 26 '20 at 13:55
  • 1
    Ps. You probably shouldn't wrap those calls to `Start` / `Stop` in `Task.Run`. Instead just do it synchronously and return `Task.CompletedTask`. – Joelius Nov 26 '20 at 13:56
  • The methods are non blocking, they just kick off workers. – uriDium Nov 27 '20 at 05:28
  • That doesn't matter. As long as they're synchronous there's no reason to wrap them in `Task.Run` (in this scenario). – Joelius Nov 27 '20 at 08:50
  • Oh sorry, misunderstood. I thought you wanted me to wrap each one in Task.Run – uriDium Nov 27 '20 at 09:05

0 Answers0