Problem with serial port data receive in C#

前端 未结 6 1940
梦谈多话
梦谈多话 2021-01-15 21:40

I have a problem with a C# program. Through the Serial port i Receive a large string about 110 characters. This part works ok, but when i add code to split the string up i r

6条回答
  •  一生所求
    2021-01-15 22:03

    This is typical behavior for a serial port. They are very slow. When the DataReceived event fires, you'd typically only get one or two characters. Notably is that it works well when you debug because single-stepping through the code gives the serial port lots of time to receive additional characters. But it will go Kaboom as soon as you run without a debugger because the string isn't long enough.

    You'll need to modify the code by appending the string you receive to a string variable at class scope. Only parse the string after you've received all the characters you expected. You'll need some way to know that you've received the full response. Most typically serial devices will terminate the string with a special character. Often a line-feed.

    If that's the case then you can make it easy by setting the SerialPort.NewLine property to that terminator and calling ReadLine() instead of ReadExisting().

提交回复
热议问题