如何同时写入和读取串行端口?

how to write and read to serialPort in same time?

我有一些设备需要使用串行端口进行连接。 该设备从我这边接收命令并向我发送数据。 我在同一 class => 同一线程中执行所有 send/receive。

我已经连接到这个设备,并且我成功地 send/receive 命令和数据 from/to 这个设备。

我需要每 25 毫秒发送一次的命令之一是 'give me your status' - 这意味着我要求设备发回一些带有数据的结构。

万一我丢失了一些接收数据...当我做 'serialPortStream.BytesToRead'(测试是否有一些数据要获取)时,我会在我的 ByteReading 上找到我还没有 rad 的旧缓冲区吗? 如果我错过了我需要阅读的最后一个包裹,或者收到的新数据可能会删除之前收到的旧数据,我会有多少包裹?

使用 OnRecieveData 处理程序将数据保存到 ConcurrentQueue 或类似的东西。

namespace Test
{   class Program
    {
        const int bufSize = 2048;
        static void Main(string[] args)
        {

            Byte[] buf = new Byte[bufSize]; 
            SerialPort sp = new SerialPort("COM1", 115200);
            sp.DataReceived += port_OnReceiveData; // Add DataReceived Event Handler

            sp.Open();

            // Wait for data or user input to continue.
            Console.ReadLine();


            sp.Close();
        }

        private static void port_OnReceiveData(object sender,  SerialDataReceivedEventArgs e)
        {
            SerialPort port = (SerialPort) sender;
            switch(e.EventType)
            {
                case SerialData.Chars:
                {
                    Byte[] buf = new Byte[bufSize];
                    port.Read(buf, 0, bufSize)
                    Console.WriteLine("Recieved data! " + buf.ToString());
                    break;
                }
                case SerialData.Eof:
                {
                    // means receiving ended
                    break;
                }
            }
        }
    }
}