Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Service: Multiple instances of the same service class?

When you create a Windows Service, you create a list of the services you want to start. The default is this:

ServicesToRun = New System.ServiceProcess.ServiceBase() {New Service}

Can you have multiple instances of the same Service class (that bind to different addresses or ports), like this?

ServicesToRun = New System.ServiceProcess.ServiceBase() {New Service("Option1"), New Service("Option2")}

Or will that cause problems? Should we use two different classes instead? What's the best approach to this problem?

like image 977
qJake Avatar asked May 03 '11 14:05

qJake


1 Answers

A service by itself doesn't bind to addresses or ports. You can make the service start threads or tasks that do, so one service could start threads for listening to e.g. http and other addresses:ports or whatever you want it to do.

The following example shows you what I mean, it's in C# but if it doesn't translate well to you then use this to translate. My Main function would in your case be the Start function of your service.

public abstract class ServiceModuleBase
{
    public abstract void Run();
}

public class SomeServiceModule : ServiceModuleBase
{
   //Implement Run for doing some work, binding to addresses, etc.
}

public class Program
{

    public static void Main(string[] args)
    {

        var modules = new List<ServiceModule> {new SomeServiceModule(), new SomeOtherServiceModule()};

        var tasks = from mod in modules
                    select Task.Factory.StartNew(mod.Run, TaskCreationOptions.LongRunning);

        Task.WaitAll(tasks.ToArray());


        Console.Out.WriteLine("All done");
        Console.ReadKey();


    } 
}

Also, here is a nice summary of why your first approach doesn't work and an alternative way of how to get around that

like image 154
edvaldig Avatar answered Nov 15 '22 05:11

edvaldig