2008-10-07 60 views
150

我在C#(運行於XP嵌入式)上運行的應用程序正在與作爲Windows服務實現的「看門狗」通信。設備啓動時,此服務通常需要一段時間才能啓動。我想從我的代碼中檢查服務是否正在運行。我怎樣才能做到這一點?如何驗證Windows服務是否正在運行

回答

290

我想這樣的事情會的工作:

添加System.ServiceProcess到您的項目引用(這是.NET選項卡上)。

的快捷方式:

return new ServiceController(SERVICE_NAME).Status == ServiceControllerStatus.Running; 

的更安全的方式:

try 
{ 
    using(ServiceController sc = new ServiceController(SERVICE_NAME)) 
    { 
     return sc.Status == ServiceControllerStatus.Running; 
    } 
} 
catch(ArgumentException) { return false; } 
catch(Win32Exception) { return false; } 

的詳細方法:

using System.ServiceProcess; 

// 

ServiceController sc; 
try 
{ 
    sc = new ServiceController(SERVICE_NAME); 
} 
catch(ArgumentException) 
{ 
    return "Invalid service name."; // Note that just because a name is valid does not mean the service exists. 
} 

using(sc) 
{ 
    ServiceControllerStatus status; 
    try 
    { 
     sc.Refresh(); // calling sc.Refresh() is unnecessary on the first use of `Status` but if you keep the ServiceController in-memory then be sure to call this if you're using it periodically. 
     status = sc.Status; 
    } 
    catch(Win32Exception ex) 
    { 
     // A Win32Exception will be raised if the service-name does not exist or the running process has insufficient permissions to query service status. 
     // See Win32 QueryServiceStatus()'s documentation. 
     return "Error: " + ex.Message; 
    } 

    switch(status) 
    { 
     case ServiceControllerStatus.Running: 
      return "Running"; 
     case ServiceControllerStatus.Stopped: 
      return "Stopped"; 
     case ServiceControllerStatus.Paused: 
      return "Paused"; 
     case ServiceControllerStatus.StopPending: 
      return "Stopping"; 
     case ServiceControllerStatus.StartPending: 
      return "Starting"; 
     default: 
      return "Status Changing"; 
    } 
} 

編輯:另外還有一點需要一個期望的狀態的方法sc.WaitforStatus()和超時,從未使用它,但它可能適合您的需求。

編輯:一旦你獲得狀態,再次獲得狀態,你需要先撥打sc.Refresh()

參考:ServiceController .NET中的對象。

18

請看看.NET中的ServiceController對象。

+2

Oooh ...甚至比通過WMI滾動自己的更好。我會刪除我的答案。 – EBGreen 2008-10-07 12:12:50

+3

@EBGreen - 我不知道,WMI路線可能對未來的其他人有用,有不止一種方式來剝皮貓,以及所有這些.... – Carl 2008-10-07 12:16:06

9

在這裏,您可以在本地機器中獲得所有可用服務及其狀態。

ServiceController[] services = ServiceController.GetServices(); 
foreach(ServiceController service in services) 
{ 
    Console.WriteLine(service.ServiceName+"=="+ service.Status); 
} 

您可以比較內環service.name物業服務,你會得到你的服務的狀態。 詳情請去http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.aspxhttp://msdn.microsoft.com/en-us/library/microsoft.windows.design.servicemanager(v=vs.90).aspx

相關問題