2008-10-07 39 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

相关问题