正确实现异步SerialPort读取 [英] Correct Implementation of Async SerialPort Read

查看:268
本文介绍了正确实现异步SerialPort读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里阅读了一些建议将port.BaseStream.ReadAsync()与waith异步/等待一起使用的线程.对我来说不清楚的是实现此目标的最佳方法是什么?

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.

推荐答案

Microsoft更新了API,该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 DataReceivedBytesToRead等问题API成员.他建议使用BaseStream来建议这种方法,而不是使用SerialPort API,因为他指出该API的设计,实施和测试不佳:

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();

请注意,我发现将BCL与BaseStream一起使用时的性能提高比使用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.

这篇关于正确实现异步SerialPort读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆