问题
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