2011-06-15 58 views
9

我有一个在所有域计算机上运行WMI查询以查找登录用户的.NET应用程序;它会ping每台计算机以查找它是否在线,然后运行实际查询。如何设置WMI查询的超时时间?

代码片段:

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查询无限期地挂起。

如何设置超时时间?

回答

12

的ManagementObjectSearcher有一个Options特性:可用选项之一是TimeoutTimeSpan类型:

获取或设置超时适用于 操作。请注意,对于 操作返回集合, 此超时适用于 枚举向所得 收藏,不操作本身 (该ReturnImmediately属性是用于后者 )。此属性为 ,用于表示半同步执行操作 应执行 。

+0

很好,它的工作原理。 – Massimo 2011-06-15 09:48:33

6

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

+0

这仅用于连接,不用于实际查询;无论如何,如果连接需要花费太多时间(防火墙等);但在我的情况下,它是挂起的*查询*。 – Massimo 2011-06-15 09:49:23