2012-01-30 224 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服務時,您希望爲您的服務設置依賴關係。然後,當用戶在服務管理器中啓動服務時,它將自動嘗試啓動依賴服務。