Clear serial port receive buffer in C#

后端 未结 4 1369
北海茫月
北海茫月 2020-12-15 08:57

Just want to know how do we clear the receive buffer of my serial port in C#. Seems like the data in the receive buffer just keep accumulating. For example, the flow of inc

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-15 09:28

    There are two buffers. One buffer is associated with the serial port and the other with its base stream, where data from the port buffer is streamed into. DiscardIn Buffer() just gets data from the Serial Port buffer discarded. There is still data in the Base Stream that you will read. So, besides using DiscardInBuffer, also use SP.BaseStream.Flush(). Now you have a clean slate! If you are not getting a lot of data, simply get rid of the base stream: SP.BaseStream.Dispose().

    Since you are still getting the data received event, yo can read it and not put yourself in jeopardy of losing data.

提交回复
热议问题