UWP SerialDevice.FromIdAsync throws “Element not found” (Exception from HRESULT: 0x80070490) on Windows 10

心不动则不痛 提交于 2019-12-14 03:51:43

问题


I want to open serial port on an attached Bluetooth device in a Xamarin Forms application.

Here is the code (I simplified it in order to illustrate the problem):

  string l_gdsSelector = SerialDevice.GetDeviceSelector();
  var l_ardiDevices = await DeviceInformation.FindAllAsync(l_gdsSelector);

  foreach(DeviceInformation l_diCurrent in l_ardiDevices)
  {
    if(l_diCurrent.Name.StartsWith("PX05"))
    {
      m_sdDevice = await SerialDevice.FromIdAsync(l_diCurrent.Id);

      break;
    }
  }

This code throws "Element not found" (Exception from HRESULT: 0x80070490) Exception at await SerialDevice.FromIdAsync

I cannot believe it : "Element not found" whereas DeviceInformation.FindAllAsync juste returned it as an existing device !

Can someone explain me this strange behavior? and predominatingly how to solve it?

Thank you in advance


回答1:


The first call to DeviceInformation.FindAllAsync function must be made in UI thread. as this code is a part of a DLL, I decided to always call it in the UI thread.

So here is my modified code :

  TaskCompletionSource<bool> l_tcsResult = new TaskCompletionSource<bool>();

  await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
    Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
    {
      try
      {
        m_sdDevice = await SerialDevice.FromIdAsync(p_strDeviceID);

        l_tcsResult.SetResult(true);
      }
      catch (Exception l_exError)
      {
        l_tcsResult.SetException(l_exError);

        System.Diagnostics.Debug.WriteLine(l_exError);
      }
    });

  await l_tcsResult.Task;

To allow application to communicate with serial device, please edit package manifest and add following entry in section:

<DeviceCapability Name="serialcommunication">
  <Device Id="any">
    <Function Type="name:serialPort" />
  </Device>
</DeviceCapability>


来源:https://stackoverflow.com/questions/38845320/uwp-serialdevice-fromidasync-throws-element-not-found-exception-from-hresult

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!