问题描述
我在这里阅读了一些线程,建议将 port.BaseStream.ReadAsync()
与等待异步/等待一起使用.我不清楚实现这一点的最佳方法是什么?
I have read a few threads here suggesting to use port.BaseStream.ReadAsync()
with waith async / await. What is not clear to me is what is the best way to implement this?
我是否仍然使用 event_handler 并使其异步/可等待?
Do i still use the event_handler and just make it async / awaitable ?
private async void myPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] buffer = new byte[myPort.BytesToRead];
await (myPort.BaseStream.ReadAsync(buffer, 0, buffer.Length));
}
或者是事件处理程序被完全忽略,而是我在循环中调用 ReadAsync?
Or is the event handler ignored completely and instead i am calling ReadAsync in a loop?
一旦解析,我将 1) 将数据发送到 TCP 服务器和 2) 将其写入 sq3lite 数据库.
Once parsed, I will be 1) Sending the data to a TCP Server and 2) Write it to sq3lite database.
推荐答案
微软更新了 API,可以实现相对简单的异步读写实现.请注意,您不会实现您似乎已经完成的同步事件处理程序,而是在您希望在 COM 端口上接收数据时调用此函数:
Microsoft has updated the API which can allow for a relatively simple async read and write implementation. Please note that you would not implement the synchronous event handler which is what you appear to have done, but simply call this function whenever you expect to receive data on the COM port:
public async Task<Stream> ReceiveData()
{
var buffer = new byte[4096];
int readBytes = 0;
SerialPort port = new SerialPort(/* ... */);
using (MemoryStream memoryStream = new MemoryStream())
{
while ((readBytes = await port.BaseStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
memoryStream.Write(buffer, 0, readBytes);
}
return memoryStream;
}
}
这是另一种替代实现(参见 http://www.sparxeng.com/blog/software/must-use-net-system-io-ports-serialport),其中作者解释了 SerialPort DataReceived
的问题,BytesToRead
和其他 API 成员.他没有使用 SerialPort API,因为他表示它的设计、实现和测试都很差,他建议使用 BaseStream
的这种方法:
Here is another alternative implementation (see http://www.sparxeng.com/blog/software/must-use-net-system-io-ports-serialport) where the author explains problems with the SerialPort DataReceived
, BytesToRead
, and other API members. Instead of using the SerialPort API because he indicates it has been poorly designed, implemented and tested he suggests this methodology using the BaseStream
:
Action kickoffRead = null;
kickoffRead = delegate {
port.BaseStream.BeginRead(buffer, 0, buffer.Length, delegate (IAsyncResult ar) {
try {
int actualLength = port.BaseStream.EndRead(ar);
byte[] received = new byte[actualLength];
Buffer.BlockCopy(buffer, 0, received, 0, actualLength);
raiseAppSerialDataEvent(received);
}
catch (IOException exc) {
handleAppSerialError(exc);
}
kickoffRead();
}, null);
};
kickoffRead();
请注意,我发现使用带有 BaseStream
的 BCL 的性能改进比使用 SerialPort API 好很多数量级.
Please note that the performance improvements I have found using the BCL with BaseStream
are many orders of magnitude better than using the SerialPort API.
这篇关于Async SerialPort Read 的正确实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!