简体   繁体   中英

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?

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 eg 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM