不知道有没有更好的方法,所以这就是问题的原因。我可以使用以下代码检查特定机器上是否存在服务:
bool DoesServiceExist(string serviceName, string machineName)
{
ServiceController controller = null;
try
{
controller = new ServiceController(serviceName, machineName);
controller.Status;
return true;
}
catch(InvalidOperationException)
{
return false;
}
finally
{
if (controller != null)
{
controller.Dispose();
}
}
}
但对于我来说,这似乎是一个效率低下的解决方案(由于异常处理)。有没有更好的方法来检查服务是否存在?注意-我最近已经切换到.NET 4.0,所以如果有人知道4.0中更好的解决方案,这是可以接受的。
编辑:
下面是一个示例C控制台应用程序,用于测试我的示例以及GetServices代码示例的性能。在我的测试中,我发现getServices在服务不存在的情况下更具性能,但在服务确实存在的情况下慢了两倍:
static void Main(string[] args)
{
string serviceName = string.Empty;
string machineName = string.Empty;
var sw = new Stopwatch();
sw.Reset();
sw.Start();
for (int i = 0; i < 1000; i++)
{
ServiceExistsException(serviceName, machineName);
}
sw.Stop();
Console.WriteLine("Elapsed time: " + sw.ElapsedMilliseconds.ToString());
sw.Reset();
sw.Start();
for (int i = 0; i < 1000; i++)
{
ServiceExistsGetList(serviceName, machineName);
}
sw.Stop();
Console.WriteLine("Elapsed time: " + sw.ElapsedMilliseconds.ToString());
Console.WriteLine("Done");
Console.ReadLine();
}
static bool ServiceExistsException(string serviceName, string machineName)
{
ServiceController controller = null;
try
{
controller = new ServiceController(serviceName, machineName);
string name = controller.DisplayName;
return true;
}
catch (InvalidOperationException)
{
return false;
}
finally
{
if (controller != null)
{
controller.Dispose();
}
}
}
static bool ServiceExistsGetList(string serviceName, string machineName)
{
ServiceController[] services = null;
try
{
services = ServiceController.GetServices(machineName);
var service = services.FirstOrDefault(s => s.ServiceName == serviceName);
return service != null;
}
finally
{
if (services != null)
{
foreach (ServiceController controller in services)
{
controller.Dispose();
}
}
}
}
}