【问题标题】:Multiple Windows Services under the same process not starting同一进程下的多个 Windows 服务无法启动
【发布时间】:2009-11-06 00:10:17
【问题描述】:

我们正在尝试实现在同一进程下启动多个服务的单个 Windows 服务。根据代码,我看到您执行以下操作:

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

但是,此代码只执行 Service1 而不是 Service2。 Service1 和 Service2 都是自己执行的。有什么想法吗?

【问题讨论】:

  • 您是在寻找两个独立的物理 Windows 服务还是一个执行两个功能的 Windows 服务?
  • 您的 Service1/Service2 看起来如何?他们同时拥有 OnStart 方法和不同的 ServiceName?
  • @Anders 是的。事实上,两者都可以单独启动和运行。
  • 我在这个问题上找到了一个类似的线程。 stackoverflow.com/questions/816437/…
  • 所以我们最终解决了我们的问题,而是使用一个托管多个服务的项目,这些服务安装程序又创建了三个不同的 Windows 服务。无论如何,这是一个更好的解决方案,因为我们可以在发生某种故障时独立启动和停止各个服务。

标签: c# .net windows-services


【解决方案1】:

我认为您会想要创建一个子服务模型,其中可以从主 Windows 服务启动任意数量的子服务。

public interface ISubService
{
   void Initialize( XmlElement xmlSection );
   bool Start( );
   void RequestStop( );
   void Stop( TimeSpan timeout );
}

然后可能是一个基本的线程服务类..

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( ) { ... }
}

然后,您只需为子服务创建所需的许多基于线程服务的类,然后将它们全部放入 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( )。

希望有帮助!

【讨论】:

  • 这是一个有趣的想法。这是否允许我们独立编译新库并将它们添加到服务中,而无需通过将它们添加到 app.config 来重新编译服务?这将是一个非常可扩展的解决方案!
  • 是的,这完全是这个解决方案的意图。我们不断地添加迷你服务,不想接触 Windows 服务处理程序。在应用配置中添加一个新行,你就很好了。
猜你喜欢
  • 2018-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多