【发布时间】:2020-07-08 12:49:58
【问题描述】:
我正在将功能从示例 Windows 窗体应用程序移植到 Xamarin.Forms UWP 应用程序,它应该在 COM 端口上写入和读取蓝牙设备。我大部分时间都可以正常工作,但 UWP 应用程序会间歇性地进入任何对 dataReader.LoadAsync 的调用都会触发异常的状态:
Exception thrown at 0x74AF1A62 (KernelBase.dll) in MyApp.UWP.exe: WinRT originate error - 0x800710DD : 'The operation identifier is not valid.'.
Exception thrown: 'System.Runtime.InteropServices.COMException' in MyApp.UWP.exe
WinRT information: The operation identifier is not valid.
重新启动应用程序或 Visual Studio 没有帮助,问题仍然存在。
最后一次发生它似乎并没有影响我的 dataWriter 写入设备,只影响后续读取。
所有代码都在 UWP 项目中。
private DataReader _dataReader;
private DataWriter _dataWriter;
private SerialDevice _currentSerialDevice;
private async Task ReadAsync(SerialDevice serialDevice)
{
const uint ReadBufferLength = 1024;
if (_dataReader == null)
{
_dataReader = new DataReader(_currentSerialDevice.InputStream) { InputStreamOptions = InputStreamOptions.Partial };
}
uint bytesRead = await _dataReader.LoadAsync(ReadBufferLength); // <- exception here
if (bytesRead > 0)
{
var vals = new byte[bytesRead];
_dataReader.ReadBytes(vals);
DoStuffWithBytes(vals);
}
}
串行设备是从应用程序的列表中选择的。
// Get serial devices
DeviceInformationCollection serialDeviceCollection = await DeviceInformation.FindAllAsync(SerialDevice.GetDeviceSelector());
// Load serial device from user choosing a device from serialDeviceCollection
public async void ConnectToSerialDevice(DeviceInformation device)
{
_currentSerialDevice = await SerialDevice.FromIdAsync(device.Id);
_currentSerialDevice.BaudRate = 115200;
_currentSerialDevice.Parity = SerialParity.None;
_currentSerialDevice.DataBits = 8;
_currentSerialDevice.StopBits = SerialStopBitCount.One;
_currentSerialDevice.Handshake = SerialHandshake.RequestToSend;
}
写入设备的代码,即使处于奇数状态也能正常工作:
private async Task WriteToDevice(byte[] outBuffer)
{
if (_currentSerialDevice != null)
{
if (_dataWriter == null)
{
_dataWriter = new DataWriter(_currentSerialDevice.OutputStream);
}
_dataWriter.WriteBytes(outBuffer);
await _dataWriter.StoreAsync();
}
}
我尝试过刷新数据写入器、每次都重新创建数据写入器和数据读取器等操作,但我仍然遇到相同的错误并且无法从设备读取任何内容。在正常操作中,我能够成功读取我期望的字节(即使没有要读取的字节,它也会“读取”0字节)并且可以毫无例外地输出这个结果。
关于这一切的奇怪之处在于,即使原始 Windows Forms 应用程序进入此状态后,它不仅可以正常工作(使用相同的蓝牙设备),而且只需打开端口并从设备读取(在旧的app) 实际上暂时修复了 UWP 应用程序中的问题,让我可以再次从设备读取。
【问题讨论】:
标签: c# uwp serial-port