2012-01-30 199 views
-1

我正在写一个Windows服务,检查特定服务并检查它。如果是停止将开始它...启动Windows服务

protected override void OnStart(string[] args) 
    { 
     Thread thread = new Thread(new ThreadStart(ServiceThreadFunction)); 
     thread.Start(); 
    } 

public void ServiceThreadFunction() 
    { 

     try 
     { 
      ServiceController dc = new ServiceController("WebClient"); 

      //ServiceController[] services = ServiceController.GetServices(); 

      while (true) 
      { 

       if ((int)dc.Status == 1) 
       {     


        dc.Start(); 
        WriteLog(dc.Status.ToString); 
        if ((int)dc.Status == 0) 
        { 

         //heartbeat 
        } 


       } 
       else 
       { 
        //service started 
       } 
       //Thread.Sleep(1000); 
      } 
     } 
     catch (Exception ex) 
     { 
     // log errors 
     } 
    } 

我希望服务检查其他业务,并开始... plz帮助我,我怎么能做到这一点

+0

你使用的代码有什么问题?哪里出问题了? – 2012-01-30 13:08:56

+0

为什么你将枚举转换为整数而不是直接与适当的枚举值进行比较?这会让这个更具可读性。 – 2012-01-30 13:12:15

回答

5

首先,为什么你是否将方便的ServiceControllerStatus枚举的ServiceController的Status属性转换为int?最好把它作为一个枚举。特别是因为你的Heartbeat代码将它与0进行比较,因为ServiceControllerStatus没有0作为可能的值,所以永远不会运行。其次,你不应该使用while(true)循环。即使使用Thread.Sleep,你在那里已经发表了评论,这是不必要的资源消耗。你可以只使用WaitForStatus方法等待服务启动:

ServiceController sc = new ServiceController("WebClient"); 
if (sc.Status == ServiceControllerStatus.Stopped) 
{ 
    sc.Start(); 
    sc.WaitForStatus (ServiceControllerStatus.Running, TimeSpan.FromSeconds(30)); 
} 

这将等待30秒(或其他)的服务,以达到运行状态。

UPDATE:我重新读了原来的问题,我认为你在这里试图做的甚至不应该用代码来完成。如果我理解正确,那么在安装WebClient服务时,您希望为您的服务设置依赖关系。然后,当用户在服务管理器中启动服务时,它将自动尝试启动依赖服务。