【发布时间】:2010-10-20 18:14:32
【问题描述】:
不知道是否有更好的方法来做到这一点,所以这就是问题的原因。我可以使用以下代码检查特定机器上是否存在服务:
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();
}
}
}
}
}
【问题讨论】:
标签: c# windows-services