views:

524

answers:

2

Is it safe to read and write to a serial port at the same time via different threads (one read thread and one write thread)? Would it be necessary to add locking around reading/writing in each thread?

+2  A: 

From the documentation of SerialPort:

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

Since Read and Write are not static, they would not be threadsafe. It's a very bad idea, in any case, since the SerialPort class maintains internal buffers for you.

You'll need to synchronize your I/O to your serial port.

Reed Copsey
But the SerialPort is a special case, consisting of separate Read and Write channels in both soft- and hardware. Using 2 Read threads would require locking.
Henk Holterman
Yeah - it should be okay, provided your reader thread never writes, and your writer thread never reads, BUT - this is an implementation detail, and the documentation doesn't specifically say this is allowed, so theoretically, this could change in a future version of .NET. Also, I wouldn't guarantee that this is the behavior on other platforms, such as if you use SerialPort on the CF. I wouldn't do it, personally, since the API's documentation doesn't explicitly allow it.
Reed Copsey
+3  A: 

Reading and writing to the serial port "at the same time" from different threads is a standard way to handle serial port communications: one thread handles reading, and one handles writing. Acceptable.

There are a number of serial-based devices that send data asynchronously to the host machine while still allowing commands to be sent to the device itself: devices such as barcode scanners, tag scanners and cameras.

Problems?

Problems arise when you attempt to synchronize your communication to and from the device.

For instance, you want to write a command and then immediately read back any response. Well, in that case you would suspend the reading thread and manually read off all the serial port data after having written the command. After the command has been processed, the reading thread can start up again.

Summary

In general through, I would suggest only have one extra thread that processes all the reading of port data and fires off events, such as DataReceived and perform all your writes from your main thread.

Mike J
Mike J, that would be 1 *extra* thread. I assume you intend to write from the main thread?
Henk Holterman
Yip. Generally that's the approach I've found to be acceptable. But as I've found, the issue really lies in the synchronization of the reads and writes and boy that can be a downright pain :-)
Mike J