Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Thread.Sleep() before SerialPort.Open and Close?

Tags:

c#

serial-port

I notice sample codes I read on SerialPort closing and opening where people would add Thread.Sleep(1000) before SerialPort.Open() and Close(). Like the following:

Thread.Sleep(1000);
serialPort1.Open();
/* some code */
Thread.Sleep(1000);
serialPort1.Close();

I cannot find any explanation anywhere. Why do people block the serial port using Thread.Sleep before it gets Open or Close? Is it for some timing purpose? Am I supposed to put a Thread.Sleep whenever I read from or write to Serial Port as well?

like image 809
KMC Avatar asked Jun 22 '11 02:06

KMC


2 Answers

When you open a port, the SerialPort class fires up a new thread under the hood which is responsible (via the WaitCommEvent Windows API function) for waiting for serial port activity (e.g. data arrived) and firing the appropriate events to your handlers. That's why events like DataReceived actually occur on a secondary thread.

When you close the port, the Close() call returns immediately but it takes some time for the secondary thread to spin down.

If you attempt to re-open the port too quickly after calling Close, and the thread hasn't yet spun down, then the SerialPort instance is not in a state where it can begin a new connection.

Note the MSDN documentation for SerialPort.Close states:

The best practice for any application is to wait for some amount of time after calling the Close method before attempting to call the Open method, as the port may not be closed instantly.

You could keep track of when you closed the port, and before opening it again make sure some arbitrary timeout has elapsed.

No need to sleep before reads / writes, although a few quirks to keep in mind:

  • Read can return less bytes than you ask for
  • Sometimes the DataReady event doesn't fire
  • ReadTimeout can be buggy

Keep in mind the SerialPort class in the .NET BCL still relies on the underlying Win32 API, and I don't think it's gotten a lot of love from Microsoft since the initial implementation.

For more information see:

  • http://www.innovatic.dk/knowledg/SerialCOM/SerialCOM.htm#SerialPortEvents

  • http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/f334ecce-eca3-46fd-8b65-27c02a1d4fea#10dae30d-bc75-49bb-a669-79399e58e1cc

  • SerialPort class occasionally hangs on Dispose

like image 122
rkagerer Avatar answered Sep 28 '22 02:09

rkagerer


Only one open connection can exist per SerialPort object. The best practice for any application is to wait for some amount of time after calling the Close method before attempting to call the Open method, as the port may not be closed instantly.

Have a look at this link.

like image 22
Bibhu Avatar answered Sep 28 '22 01:09

Bibhu