3

In our .NET application we set up the following queries to detect when any USB device was added or removed:

SELECT * FROM __InstanceCreationEvent
WITHIN 0.5
WHERE TargetInstance ISA 'Win32_PnPEntity'

and

SELECT * FROM __InstanceDeletionEvent
WITHIN 0.5
WHERE TargetInstance ISA 'Win32_PnPEntity'

When we start listening to these queries we can see the process WMI Provider host acquiring a full CPU core.

Are the above queries inefficient?
Is there a better way to detect when a USB device was attached apart from polling every x seconds? Note that the USB devices we want to detect aren't attached as drives, they are security dongles.

Johannes Egger
  • 3,874
  • 27
  • 36
  • Possible duplicate of [Detecting USB drive insertion and removal using windows service and c#](http://stackoverflow.com/questions/620144/detecting-usb-drive-insertion-and-removal-using-windows-service-and-c-sharp) – magicandre1981 Oct 25 '16 at 15:16
  • also helpful: http://www.codeproject.com/Articles/18062/Detecting-USB-Drive-Removal-in-a-C-Program – magicandre1981 Oct 25 '16 at 15:17
  • Thanks, I guess I was too unclear about the type of USB devices we want to detect. They are not standard flash drives, but security dongles. I.e. they don't attach as hard drives to the computer. – Johannes Egger Oct 27 '16 at 04:17
  • have you tried the code? – magicandre1981 Oct 27 '16 at 04:21
  • Nope, but the StackOverflow question queries `Win32_VolumeChangeEvent` which is [documented](https://msdn.microsoft.com/en-us/library/aa394516%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396) as `represents a local drive event that results from the addition of a drive letter or mounted drive on the computer system`. I didn't try the CodeProject thing but it looks too complicated and brittle for such a *simple thing*. – Johannes Egger Oct 27 '16 at 04:39
  • 1
    It seems that the interval in the within clause is just too short. 0.5 seconds... that should have been obvious. So instead of having WMI doing the polling we ended up with custom polling using Rx's `Observable.Interval`. – Johannes Egger Oct 27 '16 at 04:42
  • I link to answer that use native APIs to get notifications about USB device insert/remove events. I have no idea why you still talk about WMI – magicandre1981 Oct 27 '16 at 15:06
  • @JohannesEgger Can you please provide the example code on how you solved the problem? – Jinjinov May 04 '20 at 19:38
  • Sorry, I don't have access to that project anymore. And I can't remember off the top of my head. – Johannes Egger May 04 '20 at 21:18

0 Answers0