gpt4 book ai didi

c# - 如何为 WMI 查询设置超时?

转载 作者:太空狗 更新时间:2023-10-29 17:37:15 26 4
gpt4 key购买 nike

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

Gets or sets the time-out to apply to the operation. Note that for operations that return collections, this time-out applies to the enumeration through the resulting collection, not the operation itself (the ReturnImmediately property is used for the latter). This property is used to indicate that the operation should be performed semi-synchronously.

关于c# - 如何为 WMI 查询设置超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6355616/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com