【发布时间】:2011-06-01 01:06:39
【问题描述】:
我编写了一个 Windows 服务,它将 WCF 服务公开给安装在同一台机器上的 GUI。当我运行 GUI 时,如果我无法连接到服务,我需要知道是因为尚未安装服务应用程序,还是因为服务没有运行。如果是前者,我想安装它(如here 所述);如果是后者,我会想启动它。
问题是:如何检测服务是否已安装,然后检测到已安装,如何启动?
【问题讨论】:
标签: c# wcf windows-services
我编写了一个 Windows 服务,它将 WCF 服务公开给安装在同一台机器上的 GUI。当我运行 GUI 时,如果我无法连接到服务,我需要知道是因为尚未安装服务应用程序,还是因为服务没有运行。如果是前者,我想安装它(如here 所述);如果是后者,我会想启动它。
问题是:如何检测服务是否已安装,然后检测到已安装,如何启动?
【问题讨论】:
标签: c# wcf windows-services
用途:
// add a reference to System.ServiceProcess.dll
using System.ServiceProcess;
// ...
ServiceController ctl = ServiceController.GetServices()
.FirstOrDefault(s => s.ServiceName == "myservice");
if(ctl==null)
Console.WriteLine("Not installed");
else
Console.WriteLine(ctl.Status);
【讨论】:
.GetServices() 返回 100 个 ServiceController 对象,而您已经处理了 100 个对象中的一个,而忽略了其余对象,那真的会更好吗?我自己不会这么说。
您也可以使用以下内容..
using System.ServiceProcess;
...
var serviceExists = ServiceController.GetServices().Any(s => s.ServiceName == serviceName);
【讨论】:
GetServices(string)
其实是这样循环的:
foreach (ServiceController SC in ServiceController.GetServices())
如果运行您的应用程序的帐户无权查看服务属性,则可能会引发访问被拒绝异常。另一方面,即使不存在具有此类名称的服务,您也可以安全地执行此操作:
ServiceController SC = new ServiceController("AnyServiceName");
但如果服务不存在访问其属性将导致 InvalidOperationException。因此,这是一种检查服务是否已安装的安全方法:
ServiceController SC = new ServiceController("MyServiceName");
bool ServiceIsInstalled = false;
try
{
// actually we need to try access ANY of service properties
// at least once to trigger an exception
// not neccessarily its name
string ServiceName = SC.DisplayName;
ServiceIsInstalled = true;
}
catch (InvalidOperationException) { }
finally
{
SC.Close();
}
【讨论】:
对于非 linq,您可以像这样遍历数组:
using System.ServiceProcess;
bool serviceExists = false
foreach (ServiceController sc in ServiceController.GetServices())
{
if (sc.ServiceName == "myServiceName")
{
//service is found
serviceExists = true;
break;
}
}
【讨论】:
我认为这是这个问题的最佳答案。无需添加额外的处理来验证服务是否存在,因为如果不存在则会抛出异常。你只需要抓住它。如果将整个方法包装在 using() 中,也不需要 close() 连接。
using (ServiceController sc = new ServiceController(ServiceName))
{
try
{
if (sc.Status != ServiceControllerStatus.Running)
{
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 10));
//service is now Started
}
else
//Service was already started
}
catch (System.ServiceProcess.TimeoutException)
{
//Service was stopped but could not restart (10 second timeout)
}
catch (InvalidOperationException)
{
//This Service does not exist
}
}
【讨论】:
private bool ServiceExists(string serviceName)
{
ServiceController[] services = ServiceController.GetServices();
var service = services.FirstOrDefault(s => string.Equals(s.ServiceName, serviceName, StringComparison.OrdinalIgnoreCase));
return service != null;
}
【讨论】: