简体   繁体   English

c#wmi ManagementEventWatcher.Options.Timeout问题

[英]c# wmi ManagementEventWatcher.Options.Timeout issue

The code uses the wmi component in semi-synchronous mode to monitor events on a remote computer. 该代码以半同步模式使用wmi组件来监视远程计算机上的事件。 Everything works correctly until the network connection between the client and the server is interrupted. 一切正常,直到客户端和服务器之间的网络连接中断。 In this case the program remains frozen in the line: ManagementBaseObject e = watcher.WaitForNextEvent (); 在这种情况下,程序将冻结在以下行中:ManagementBaseObject e = watcher.WaitForNextEvent(); and the timeout does not work. 并且超时不起作用。 How can I manage the connection break correctly? 如何正确管理连接中断? Thank you 谢谢

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();
  }
}

I answer myself. 我回答自己。 Setting the watcher timeout to: watcher.Options.Timeout = new TimeSpan (0, 0, 0, 0, 1); 将观察者超时设置为:watcher.Options.Timeout = new TimeSpan(0,0,0,0,1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM