【发布时间】:2013-07-11 15:56:26
【问题描述】:
我正在查询远程服务器上的特定服务,试图确定这些服务的状态,并相应地启动/停止/暂停它们。
我的Server对象类的一个sn-p如下:
public class Server
{
public ManagementClass Services { get; set; }
public List<string> TargetServices { get; set; }
}
我使用 ManagementClass 对象连接到我的服务器,作为一种其他必需品(Scope、ConnectionOptions 和 ManagementPath("Win32_Service"))。TargetedServices 只是我定义的一小部分服务,我打算在我的连接结果中返回的所有服务中定位。我的 TargetedService 示例如下:
server.TargetedServices = new List<string>() { "ServiceA", "ServiceB" };
现在,当我希望从所有可用服务中找到我在我的小列表中定义的服务时,我的挣扎就开始发挥作用了……为了隔离和操纵它们。我已经完成了任务,但是处理速度非常慢。我希望找到一个聪明的,简化的解决方案。有什么想法吗?
这是我目前的 (cringe) 逻辑:
public void PingServices(List<Server> servers)
{
foreach(Server server in servers)
{
foreach(ManagementObject service in server.Services.GetInstances())
{
foreach(string target in server.TargetServices)
{
if(service.GetPropertyValue("Name").ToString() == target)
{
service.InvokeMethod("StartService", null);
}
}
}
}
}
【问题讨论】:
-
您可以在每台服务器上找到服务名称时打折。那么当你找到它们时,你可以立即停止并转移到下一个服务器上吗?您可以在多个线程上运行。您需要进行分析并找出慢的地方。
-
我同意多线程可能有助于多台服务器的进程。但是,对于只有一次服务器,此过程的速度慢得令人无法接受。我研究了 LINQ 语句,它可以将两个列表合并在一起。但是,我不能以保留 .InvokeMethod() 的方式合并
和
标签: c# linq service foreach wmi