Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to synchronize .NET SerialPort writes/reads?

In my application I use the .NET SerialPort class for reading and writing data. The reading is done using the DataReceived event, I assume internally on a ThreadPool thread. The writing is done by the UI thread (WinForms).

I was wondering, if it's necessary to synchronize the access to the SerialPort instance, so that no Reads/Writes can happen at the same time. My conscience tells me I should put locks around these calls, but I'm puzzled as all C# SerialPort examples I find on the Internet don't use locking at all.

like image 505
Mike Avatar asked Dec 10 '10 15:12

Mike


People also ask

Is SerialPort thread safe?

The data is read with the ReadFile() and written with the WriteFile() API. So the SerialPort is definitely thread safe if one thread only writes and the other thread only reads.

Can you read and write from the same serial port?

You can indeed simultaneously read and write through the serial port. At the hardware level, the serial port (the UART) is a transmitter and a receiver, which are almost independent. At the software level, they are both handled through interrupts that read from / write to a software buffer.


2 Answers

Here's a great thread on the topic, with the author of the SerialPort class participating:

MSDN: How does SerialPort handle DataReceived?

From my experience, I've written a dozen serial communication apps for use as hardware simulators, I don't lock. I didn't know at the time if I was safe or not, but in practice, I haven't had an error yet. (a year of near constant use by 20+ testers and automated test machines) That said, my applications don't leave the company, if I were writing apps for public consumption I might take more care.

like image 56
EJA Avatar answered Sep 30 '22 02:09

EJA


From the documentation:

Any public static (Shared in Visual Basic) members of this type (SerialPort) are thread safe. Any instance members are not guaranteed to be thread safe.

So you should definetly synchronize your read/writes with locks.

like image 30
weismat Avatar answered Sep 30 '22 04:09

weismat