Home > Software design >  How to start DeviceWatcher in MAUI?
How to start DeviceWatcher in MAUI?

Time:10-03

So I've managed to create a platform-specific service which task is to communicate with an USB device via HID. As the platform-specific code doesn't work as described in MAUI docs, I've done it by DI in app builder: .AddSingleton<IHidCommunicationService, HidCommunicationService>();. Thanks to this mate:)

The communication works fine but now I want to refresh devices list at runtime and to do so I wish to use DeviceWatcher in my HidCommunicationService. And here's the issue: when I try to fire the device watcher by using Start() method I get this error: A method was called at an unexpected time.

I've tried the same code in WPF app and it works fine:

string aqsFilter = HidDevice.GetDeviceSelector(usagePage, usageId, vendorId, productId);
DeviceWatcher deviceWatcher = DeviceInformation.CreateWatcher(aqsFilter);
deviceWatcher.Start();

CodePudding user response:

The problem was that deviceWatcher.Start() was fired from a wrong thread and to resolve that problem one just need to dispatch it from UI thread like this:

AppShell.Current.Dispatcher.Dispatch(() => deviceWatcher.Start());

or

App.Current.Dispatcher.Dispatch(() => deviceWatcher.Start());

  • Related