在我的WPF应用程序中,我需要获取具有特定属性的Windows服务(~200)列表。
while (current($List) !== $Current) next($List);
echo next($List);
执行此方法大约需要1分钟,并返回不可接受的数据。 看起来像searcher.Get()需要所有的时间...... 我可以做些什么来改善执行/返回时间/性能?
由于
答案 0 :(得分:0)
根据我提出的评论,希望它可以帮助某人:
public List<string> GetWindowsServicesList()
{
var result = new List<string>();
foreach (ServiceController service in ServiceController.GetServices())
{
string serviceName = service.ServiceName;
result.Add(serviceName);
}
return result;
}
public ServicesModel GetServiceProperties(string serviceName)
{
ServicesModel service = null;
string path = $"Win32_Service.Name=\"{serviceName}\"";
using (ManagementObject mngObj = new ManagementObject(path))
{
service = new ServicesModel
{
Name = mngObj.GetPropertyValue("Name") as string,
Path = mngObj.GetPropertyValue("PathName") as string,
Description = mngObj.GetPropertyValue("Description") as string,
Pid = Convert.ToInt32(mngObj.GetPropertyValue("ProcessId")),
Status = mngObj.GetPropertyValue("State") as string,
StartMode = mngObj.GetPropertyValue("StartMode") as string,
LogOnAs = mngObj.GetPropertyValue("StartName") as string
};
}
return service;
}
public List<ServicesModel> WindowsServicesCollection()
{
var result = new List<ServicesModel>();
try
{
var windowsServicesNames = GetWindowsServicesList();
for (int i = 0; i < windowsServicesNames.Count(); i++)
{
result.Add(GetServiceProperties(windowsServicesNames[i]));
}
}
catch (System.Management.ManagementException ex)
{
}
catch (System.TimeoutException ex)
{
}
return result;
}
比以前的解决方案工作得多,速度快得多,虽然看起来性能不是非常一致,而且取决于我没有发现的各种因素......