ManagementEventWatcher在c#中丢失事件



我正在开发一个使用ManagementEventWatcher监视USB事件的应用程序。代码工作正常,但在某些情况下,程序丢失了一些USB events。从USB列出所有事件的正确方法是什么?

我使用以下代码,我使用两个查询监视器连接和从usb分离。我需要监控许多USB端口。

USB监控

    ManagementEventWatcher watchUSBattach = new ManagementEventWatcher();
    ManagementEventWatcher watchUSBDettach = new ManagementEventWatcher();
    WqlEventQuery queryUsbAttach = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2 ");
    watchUSBattach.EventArrived += new EventArrivedEventHandler(watchUSBEventAdd);
    watchUSBattach.Query = queryUsbAttach;
    watchUSBattach.Start();
    WqlEventQuery queryUsbDettach = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 3");
    watchUSBDettach.EventArrived += new EventArrivedEventHandler(watchUSBEventDettach);
    watchUSBDettach.Query = queryUsbDettach;
    watchUSBDettach.Start();

我在监控usb设备插入或移除时经历过类似的事情。下面是示例代码。当WithinInterval属性设置为1ms时,我不会错过事件,而是在WMIProviderHost和相关服务中遭受不合理的CPU负载。如果我将其设置为更合理的值,如3秒,那么如果删除/创建事件从同一设备一起发生太快(例如,如果设备重置自己),我就会错过它们。也许您的查询默认的WithinInterval太长,并导致事件被删除?

WqlEventQuery q;
var scope = new ManagementScope("root\CIMV2") 
  {Options = {EnablePrivileges = true}};
q = new WqlEventQuery
{
  EventClassName = "__InstanceCreationEvent",
  WithinInterval = TimeSpan.FromMilliseconds(1),
  Condition = @"TargetInstance ISA 'Win32_USBControllerdevice'"
};
InsertWatcher = new ManagementEventWatcher(scope, q);
InsertWatcher.EventArrived += (sender, args) =>
{
  var instance = (ManagementBaseObject) args.NewEvent["TargetInstance"];
  RaiseInserted(new PlugEventArgs {DevicePath = (string) instance["__PATH"]});
};
InsertWatcher.Start();

相关内容

  • 没有找到相关文章

最新更新