UWP SerialDevice.FromIdAsync 在 Windows 10 上抛出 "Element not found"(来自 HRESULT 的异常:0x80070490)

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

我想在 Xamarin Forms 应用程序中打开连接的蓝牙设备上的串行端口。

下面是代码(为了说明问题我做了简化):

  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;
    }
  }

此代码抛出 "Element not found"(来自 HRESULT 的异常:0x80070490)异常 await SerialDevice.FromIdAsync

我简直不敢相信 : "Element not found" 而 DeviceInformation.FindAllAsync juste 将它作为现有设备退回了!

谁能给我解释一下这种奇怪的行为?主要是如何解决它?

提前致谢

必须在 UI 线程中首次调用 DeviceInformation.FindAllAsync 函数。由于此代码是 DLL 的一部分,我决定始终在 UI 线程中调用它。

这是我修改后的代码:

  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;

要允许应用程序与串行设备通信,请编辑包清单并在 <Capabilities> 部分添加以下条目:

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