简体   繁体   English

ManagementEventWatcher在C#中丢失事件

[英]ManagementEventWatcher losting events in C#

I'm developing an application that uses ManagementEventWatcher to monitor USB events. 我正在开发一个使用ManagementEventWatcher监视USB事件的应用程序。 The code works properly but in some cases the program lost some USB events . 该代码可以正常工作,但在某些情况下,该程序会丢失一些USB events What is the correct way to list all events from USB? 从USB列出所有事件的正确方法是什么?

I'm using the follow code, I'm using two queries for monitor attach and detach from usb. 我正在使用以下代码,我正在使用两个查询来进行显示器连接和从USB分离。 I need to monitor a many USB ports. 我需要监视许多USB端口。

USB Monitor 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();

I have experienced a similar thing when monitoring for usb device insertion or removal. 监视USB设备的插入或移除时,我也经历过类似的事情。 Example code below. 下面的示例代码。 When the WithinInterval property is set to 1ms then I do not miss the events but instead I suffer an unreasonable CPU load in WMIProviderHost and the associated service. WithinInterval属性设置为1ms时,我不会错过事件,但是在WMIProviderHost和关联的服务中,我会承受不合理的CPU负载。 If I set it to a more reasonable value like 3 seconds then I miss Deletion/Creation events if they occur together from the same device too quickly (for example if the device resets itself). 如果我将其设置为一个更合理的值(例如3秒),那么如果删除/创建事件在同一设备上一起发生的速度过快(例如,设备自行重置),则会错过这些事件。 Perhaps with your query the default WithinInterval is too long and is causing events to be dropped? 也许对于您的查询,默认的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();

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

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