如何在WMI查询上设置超时?

Mas*_*imo 9 .net c# wmi timeout

我有一个.NET应用程序,它在所有域计算机上运行WMI查询,以便找到登录用户; 它ping每台计算机以查找它是否在线,然后运行实际查询.

代码段:

try
{
    string loggedonuser = null;

    string computername = "ComputerToQuery";

    ConnectionOptions co = new ConnectionOptions();

    co.Username = "DOMAIN\MyUser";
    co.Password = "MyPassword";

    co.Impersonation = ImpersonationLevel.Impersonate;
    co.Authentication = AuthenticationLevel.Default;

    ManagementPath mp = new ManagementPath(@"\\" + computername + @"\root\cimv2");

    ManagementScope ms = new ManagementScope(mp,co);

    ms.Connect();

    ObjectQuery oq = new ObjectQuery("SELECT username FROM Win32_ComputerSystem");

    ManagementObjectSearcher mos = new ManagementObjectSearcher(ms,oq);

    foreach(ManagementObject mo in mos.Get())
        loggedonuser = (String) mo["username"];
}
catch(Exception e)
{
    // Handle WMI exception
}
Run Code Online (Sandbox Code Playgroud)

问题:有时WMI查询会无限期地挂起.

如何设置超时?

stu*_*rtd 12

该ManagementObjectSearcher有一个Options特性:可用选项是Timeout,类型TimeSpan:

获取或设置应用于操作的超时.请注意,对于返回集合的操作,此超时适用于通过结果集合的枚举,而不是操作本身(ReturnImmediately属性用于后者).此属性用于指示应该半同步执行操作.


mar*_*koo 6

尝试 co.Timeout = new TimeSpan(0, 0, 30);