2009-11-06 90 views
0

我们正试图在同一进程下实现一个启动多个服务的Windows服务。根据代码我看到你做以下事情:同一进程下的多个Windows服务未启动

static void Main() 
    { 
     ServiceBase[] ServicesToRun; 
     ServicesToRun = new ServiceBase[] 
     { 
      new Service1(), 
      new Service2() 
     }; 
     ServiceBase.Run(ServicesToRun); 
    } 

但是,此代码只执行Service1而不是Service2。 Service1和Service2自行执行。有任何想法吗?

+0

您是否在寻找两个独立的物理Windows服务或一个执行两个功能的Windows服务? – zac 2009-11-06 00:24:00

+0

您的Service1/Service2的外观如何?他们得到了OnStart方法和不同的ServiceName? – 2009-11-06 01:14:55

+0

@Anders是的。事实上,两人都将开始并单独运行。 – 2009-11-06 16:24:42

回答

3

我想你会想创建一个子服务模型,其中可以从主窗口服务启动任意数量的子服务。

那么也许基螺纹服务类..

public abstract class ThreadedService : ISubService 
{ 
    private Thread m_thread; 

    private ThreadedService() 
    { 
     m_thread = new Thread(new ThreadStart(StartThread)); 
    } 

    // implement the interface 
} 

通过的app.config和IConfigurationSectionHandler配置您的服务...

public class ServiceConfigurationHandler : IConfigurationSectionHandler 
{ 
    public ServiceConfigurationHandler() { } 

    public object Create(object parent, object configContext, XmlNode section) 
    { 
     return new ServiceConfiguration((XmlElement)section); 
    } 
} 

东西来处理配置部分...

public class ServiceConfiguration 
{ 
    public static readonly ServiceConfiguration Current = (ServiceConfiguration)ConfigurationManager.GetSection("me/services"); 

    private List<ISubService> m_services; 
    private string m_serviceName; 

    internal ServiceConfiguration(XmlElement xmlSection) 
    { 
     // loop through the config and initialize the services 
     // service = createinstance(type)..kind of deal 
     // m_services.Add(service); 
    } 

    public void Start() 
    { 
     foreach(ISubService service in m_services) { service.Start(); }   
    } 
    public void Stop() { ... } 
} 

那么你只需创建你需要为你的子服务,但是许多基于threadedservice类,它们都扔到的app.config ...像..

<me> 
    <services> 
    <service type="my.library.service1,my.library" /> 
    <service type="my.library.service2,my.library" /> 
    </services> 
</me> 

,最后,在实际的服务代码,只需要在启动时执行ServiceConfiguration.Current.Start(),并在出口执行Service.Configuration.Current.Stop()。

希望有帮助!

+0

这是一个有趣的想法。这是否允许我们独立地编译新库并将它们添加到服务中,而不必通过将服务添加到app.config来重新编译服务?这将是一个非常可扩展的解决方案! – 2009-11-06 16:33:26

+0

是的,这完全是这个解决方案的意图。我们不断添加迷你服务,并且不想接触Windows服务处理程序。在应用配置中放置一条新线,而且你很棒。 – Sean 2009-11-09 21:12:54