【发布时间】:2018-01-12 10:19:49
【问题描述】:
代码在半同步模式下使用 wmi 组件来监视远程计算机上的事件。 一切正常,直到客户端和服务器之间的网络连接中断。 在这种情况下,程序保持冻结在行中: ManagementBaseObject e = watcher.WaitForNextEvent(); 并且超时不起作用。 如何正确管理连接中断? 谢谢
static void Main(string[] args)
{
ConnectionOptions con1 = new ConnectionOptions();
con1.Username = networkUser;
con1.Password = networkPassword;
con1.Impersonation = ImpersonationLevel.Impersonate;
con1.EnablePrivileges = true;
con1.Authentication = AuthenticationLevel.PacketPrivacy;
ManagementPath mp1 = new ManagementPath(@"\\" + networkPath + @"\" + @"root\cimv2");
try
{
string queryString =
"SELECT * " +
"FROM __InstanceOperationEvent " +
"WITHIN 5 " +
"WHERE TargetInstance ISA 'Win32_Process' ";
WqlEventQuery wql = new WqlEventQuery(queryString);
ManagementScope Scope = new ManagementScope(mp1, con1);
Scope.Connect();
// create the watcher and start to listen
ManagementEventWatcher watcher = new ManagementEventWatcher();
watcher.Query = wql;
watcher.Scope = Scope;
watcher.Options.Timeout = TimeSpan.FromSeconds(5);
keepGoing = true;
int nError = 0;
while (keepGoing)
{
try
{
ManagementBaseObject e = watcher.WaitForNextEvent();
switch (e.ClassPath.ClassName)
{
case ("__InstanceDeletionEvent"):
{
keepGoing = false;
break;
}
default:
{
Console.WriteLine("Evento non gestito : " + e.ClassPath.ClassName);
break;
}
}
}
catch (System.Management.ManagementException e)
{
if (e.ErrorCode != ManagementStatus.Timedout)
throw;
}
}
watcher.Stop();
}
catch (Exception ex)
{
Console.WriteLine("Errore: " + ex.Message);
Console.ReadLine();
}
}
【问题讨论】: