UWP SerialDevice.FromIdAsync抛出"未找到元素" (来自HRESULT的异常:0x80070490)在Windows 10上

时间:2016-08-09 08:08:01

标签: 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 juste将其作为现有设备返回!

有人能解释我这种奇怪的行为吗?并且主要是如何解决它?

提前谢谢

1 个答案:

答案 0 :(得分:1)

必须在UI线程中首次调用DeviceInformation.FindAllAsync函数。因为这段代码是DLL的一部分,所以我决定总是在UI线程中调用它。

所以这是我修改后的代码:

func viewDidLoad() {
    super.viewDidLoad()

    mapViewHelper = GeoneMapViewHepler.init(mapView: mapView!, mapViewDelegate: self)

    ...
}

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

  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;
相关问题