由于您通过 检索服务Name
,它是 的关键属性,因此请Win32_Service class
尝试直接检索实例而不是搜索它:
string GetMyServicePath()
{
string path = "Win32_Service.Name=\"MyService\"";
using (ManagementObject service = new ManagementObject(path))
return (string) service.GetPropertyValue("PathName");
}
这是我汇总的一个快速基准,用于比较直接检索与搜索:
private const int LoopIterations = 1000;
private const string ServiceClass = "Win32_Service";
private const string ServiceName = "MyService";
private const string ServiceProperty = "PathName";
private static readonly string ServicePath = string.Format("{0}.Name=\"{1}\"", ServiceClass, ServiceName);
private static readonly string ServiceQuery = string.Format(
"SELECT {0} FROM {1} Where Name=\"{2}\"",
ServiceProperty, ServiceClass, ServiceName
);
private static ManagementObjectSearcher ServiceSearcher = new ManagementObjectSearcher(ServiceQuery);
static void Main(string[] args)
{
var watch = new Stopwatch();
watch.Start();
for (int i = 0; i < LoopIterations; i++)
{
var servicePath = GetServicePathByKey();
}
watch.Stop();
Console.WriteLine(
"{0:N0} iterations of GetServicePathByKey() took {1:N0} milliseconds",
LoopIterations, watch.ElapsedMilliseconds
);
watch.Restart();
for (int i = 0; i < LoopIterations; i++)
{
var servicePath = GetServicePathFromExistingSearcher();
}
watch.Stop();
Console.WriteLine(
"{0:N0} iterations of GetServicePathFromExistingSearcher() took {1:N0} milliseconds",
LoopIterations, watch.ElapsedMilliseconds
);
watch.Restart();
for (int i = 0; i < LoopIterations; i++)
{
var servicePath = GetServicePathFromNewSearcher();
}
watch.Stop();
Console.WriteLine(
"{0:N0} iterations of GetServicePathFromNewSearcher() took {1:N0} milliseconds",
LoopIterations, watch.ElapsedMilliseconds
);
}
static string GetServicePathByKey()
{
using (var service = new ManagementObject(ServicePath))
return (string) service.GetPropertyValue(ServiceProperty);
}
static string GetServicePathFromExistingSearcher()
{
using (var results = ServiceSearcher.Get())
using (var enumerator = results.GetEnumerator())
{
if (!enumerator.MoveNext())
throw new Exception();
return (string) enumerator.Current.GetPropertyValue(ServiceProperty);
}
}
static string GetServicePathFromNewSearcher()
{
using (var searcher = new ManagementObjectSearcher(ServiceQuery))
using (var results = searcher.Get())
using (var enumerator = results.GetEnumerator())
{
if (!enumerator.MoveNext())
throw new Exception();
return (string) enumerator.Current.GetPropertyValue(ServiceProperty);
}
}
直接枚举搜索结果的速度与我所能达到的速度差不多,比使用foreach
块快一点,比使用LINQ
. 在我的 64 位 Windows 7 Professional 系统上,ServiceName
常量设置为Power
我得到了以下结果:
1,000 iterations of GetServicePathByKey() took 8,263 milliseconds
1,000 iterations of GetServicePathFromExistingSearcher() took 64,265 milliseconds
1,000 iterations of GetServicePathFromNewSearcher() took 64,875 milliseconds