我使用这段代码来获取远程计算机上进程的好处。
代码在99.9%的情况下运行良好,但有时它会一直挂在scope.Connect()
上,即使我指定超时为10秒。
有人知道如何防止这种WMI挂断吗?
代码:
// Configure the connection settings.
ConnectionOptions options = new ConnectionOptions();
options.Timeout = new TimeSpan(0, 0, 10);
ManagementPath path = new ManagementPath(String.Format("\\\\{0}\\root\\cimv2", machine));
ManagementScope scope = new ManagementScope(path, options);
// Try and connect to the remote (or local) machine.
try {
scope.Connect();
} catch (ManagementException ex) {
// Failed to authenticate properly.
return "Failed to authenticate: " + ex.Message;
} catch (System.Runtime.InteropServices.COMException) {
// Unable to connect to the RPC service on the remote machine.
return "Unable to connect to RPC service";
} catch (System.UnauthorizedAccessException) {
// User not authorized.
return "Error: Unauthorized access";
}
有趣的是,我发现这个代码挂在哪台远程PC上。我尝试使用PowerShell连接到它,PowerShell也挂起了! 我用这个代码:
Get-WmiObject -Namespace "root\cimv2" -Class Win32_Process -ComputerName pcname