简体   繁体   English

如何使用端口基流读取完整字节

[英]How to read full bytes using port basestream

I am working on serial port communication.我正在研究串行端口通信。 While using BaseStream I am writing and reading the port.在使用BaseStream时,我正在编写和读取端口。

port.BaseStream.Write(dataItems, 0, dataItems.Length);
int receivedBytes = port.BaseStream.Read(buffer, 0, (int)buffer.Length);
Thread.Sleep(100);
var receiveData = BitConverter.ToString(buffer, 0, receivedBytes);

Hereafter write, I am sleeping the thread so that I will get full bytes.此后写,我正在休眠线程,以便获得完整的字节。 Is there any other way around that I can wait that all bytes are available?有没有其他方法可以让我等待所有字节都可用?

Note笔记

The last byte should be 22 .最后一个字节应该是22 Also the above code is running in Task named as public async Task PortHitmethod(Iterations iterations)上面的代码也在名为 public async Task public async Task PortHitmethod(Iterations iterations)的任务中运行

This is certainly a wrong way to use Stream.Read .这肯定是使用Stream.Read的错误方法。 The correct pattern is in the documentation :正确的模式在文档中:

    Stream s = new MemoryStream();
    ...
    // Now read s into a byte buffer with a little padding.
    byte[] bytes = new byte[s.Length + 10];
    int numBytesToRead = (int)s.Length;
    int numBytesRead = 0;
    do
    {
        // Read may return anything from 0 to 10.
        int n = s.Read(bytes, numBytesRead, 10);
        numBytesRead += n;
        numBytesToRead -= n;
    } while (numBytesToRead > 0);
    s.Close();

PS If you think you should use Thread.Sleep then you can be sure you are certainly doing something wrong. PS 如果你认为你应该使用Thread.Sleep那么你可以确定你肯定做错了什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM