mshsayem
mshsayem

Reputation: 18028

Why starting one service does start others (multiple services in one exe)?

I have a windows service project which consists 5 different services (single exe). In the Main method, I am using ServiceBase.Run([]) to register those:

static void Main()
{
    var servicesToRun = new ServiceBase[] 
    { 
        new ServiceA(),
        new ServiceB(),
        new ServiceC(),
        new ServiceD(),
        new ServiceE(),     
    };

    ServiceBase.Run(servicesToRun);
}

After installation, i see 5 distinct services in the service manager (services.msc). Nice, but it seems that If I start only a service (say, serviceA), other 4 services also start; though the service manager does not show started status against those services(refreshed the view also). If i manually start another service (say, serviceB) and then stop it, it seems that serviceB is no more running, but other 3 services are running.

Any idea why is this happening?

By the way: All services have this pattern:

public partial class ServiceA : ServiceBase
{
    private static readonly Timer MyTimer = new Timer(60000);   

    public ServiceA()
    {
        InitializeComponent();

        // other initializations
        ...
        ...

        MyTimer.Elapsed += <DoSomeTaskFunction>
        MyTimer.AutoReset = true;
        MyTimer.Enabled = true;
    }

    protected override void OnStart(string[] args])
    {
        myEventLog.WriteEntry("Started...");
        MyTimer.Enabled = true;
        MyTimer.Start();
    }

    ...
    ...
}

Upvotes: 1

Views: 496

Answers (2)

usr
usr

Reputation: 171246

You start working in the constructor of your services. That constructor is called in your Main method. That means that your code starts working as soon as the process starts.

It is the Enabled property of the System.Timers.Timer which says setting it true is same as Start() which was causing the problem.

Upvotes: 1

Arie
Arie

Reputation: 5373

To see in the service manager if the rest of services are really running after you started one you need to Refresh the view (context menu).

In regard to your question, there's nothing wrong with your code, and that's how it is supposed to work:

After you call Run(ServiceBase[]), the Service Control Manager ISSUES START COMMANDS, which result in calls to the OnStart methods in the services. The services are not started until the Start commands are executed. (msdn)

To start your services one by one, you need to install them separately and call ServiceBase.Run(singleService) in each

Upvotes: 0

Related Questions