Click here to Skip to main content
15,892,517 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
ih have code send receive data through serial port like below :

C#
serialPort1.WriteLine(item);
                Thread.Sleep(10000);
                sRecv = serialPort1.ReadExisting().ToString();


while sending the data and then receive the data after Thread.sleep 10 seconds, but the problem when Port did not receive the data after 10 seconds, how is it to add Thread.sleep if in the next 10 seconds if no data is received.
Posted
Comments
PIEBALDconsult 30-Aug-15 1:06am    
I prefer to spin up a Thread to handle reading.

Don't.
If you start adding Thread.Sleep to "wait" for RX data, then your UI becomes unresponsive, and your users assume your app has crashed. Particularly if it freezes for ten seconds!

Instead, handle the SerialPort.DataReceived event[^] and use a Timer to let the user know that nothing is being received.

If you aren't receiving anything, then you need to look at how your port is configured, how the device on the other end is configured, and try to get a response via HyperTerminal or similar first.
 
Share this answer
 
Wrong idea. You should not do it. Instead, you can use the separate thread which will go to the wait state without calling Thread.Sleep. When you just read from the port, and the data is not ready, it will put your thread in a wait state. It won't waste any CPU time, because the port driver works properly by hardware interrupt. Your thread will be waken up when data is ready for reading, but there are other reasons for waking up: thread abort, timeout, and so on.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900