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

我有一个.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 } 

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

如何设置超时?

ManagementObjectSearcher具有Options属性:其中一个可用选项是Timeout ,类型为TimeSpan

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

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