c# - UWP SerialDevice.FromIdAsync 抛出 "Element not found"(HRESULT 异常 : 0x80070490) on Windows 10

标签 c# bluetooth xamarin.forms uwp windows-10-universal

我想在 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;
    }
  }

此代码抛出“找不到元素”(HRESULT 异常:0x80070490)await SerialDevice.FromIdAsync 异常

我不敢相信:“找不到元素”而 DeviceInformation.FindAllAsync 只是将其作为现有设备返回!

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

提前致谢

最佳答案

第一次调用 DeviceInformation.FindAllAsync 函数必须在 UI 线程中进行。由于此代码是 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;

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

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

关于c# - UWP SerialDevice.FromIdAsync 抛出 "Element not found"(HRESULT 异常 : 0x80070490) on Windows 10,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38845320/

相关文章:

android - 可绘制 xml 资源的 Xamarin.Forms Android Resources$NotFoundException

c# - 创建列表后如何更新 Xamarin Forms ListView 的 ViewCell 属性?

javascript - 使用 Blazor 重写 JavaScript 单击和显示 UI

c# - 当用接口(interface)模糊类时,重写的实现是否仍然存在?

c# - 如何以托管方式在.NET中获取父进程

ios - 蓝牙键盘覆盖

c# - 如何更改VM中 map 的MapType?

c# - 使用 NPOI C# 将图像添加到 Excel (.xlsx)

ios - CoreBluetooth 设备名称更改

ios - 核心蓝牙 : CBPeripheral disconnects every ~10 seconds