我不知道是否有更好的方法来做这件事,所以才会提出这个问题。 我可以使用以下代码检查特定机器上是否存在某个服务:
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();
}
}
}
}
}
s.ServiceName.Equals(serviceName, StringComparison.CurrentCultureIgnoreCase)
替换==
运算符。 - ZivS