0
votes

I was thinking about a best approach to properly handle the serial port communication in my program. I have some device that sends me data, im reciving it using DataRecieved event and ReadExisting method in it. Everything that it reads is being put inside a buffer, when last line equals some string then i start to parse it into some kind of packet.

Aside from that, when i send data to this device and wait for response, i mark flag

bool isReady = false;

while(!isReady)
    Thread.Sleep(500);

And in data parsing method i set this flag to true so when I recieve packet data, code can jump out of this loop and continue to work as needed. But in my opinion this is not a clean/good way to do this. And there is a problem sometimes, if device will not send the packet I need, so program is being stuck in the loop forever.

I was wondering, how would you guys resolve this case in your code?

Thanks, and sorry for bad english.

2
Sounds like you are using the DataReceived event. Don't use it, you have no use for it. Just call Read() directly.Hans Passant

2 Answers

0
votes

Don't just wait for a response in an endless loop. Use the events like you previously mentioned to get the data. See this other SO question also. SerialPort class and DataReceived event... Getting bytes. Use ReadLine or ReadExisting? Any examples?

-1
votes

For now i've added a 5sec timeout using following code:

bool isReady = false;
DateTime timeout = DateTime.Now;
while(!isReady)
{
    Thread.Sleep(500);
    if((DateTime.Now-timeout).TotalMiliseconds >= 5000)
        break;
}

So when no response is recieved then it just jumps out of this loop. This is solving one of my problems, but still I would like to know other ways to handle this. If you guys have any ideas, please share them.