Reputation: 574
Here's my scenario: I need to read from and write to the same serial port in multiple threads. Instead of creating one SerialPort in each thread, which would cause 'access denied' error, i use kind of global cache to do the job. For each serial port, i keep only one SerialPort object.
private static object locker = new object();
internal static Dictionary<int, SerialPort> SerialPorts = new Dictionary<int, SerialPort>();
private SerialPort GetSerialPort(string port)
{
lock (locker)
{
if (!SerialPorts.ContainsKey(port))
{
SerialPort sp = new SerialPort(port, baudrate);
sp.Open();
SerialPorts[key] = sp;
}
}
return SerialPorts[key];
}
In read and write actions, I call GetSerialPort first to get the SerialPort object. Then the respective ReadByte and Write method is called. Now my question is: without any special handling, is it safe to just have multiple threads calling either ReadByte or Write methods at the same time?
Upvotes: 0
Views: 67
Reputation: 24857
'is it safe to just have multiple threads calling either ReadByte or Write methods at the same time?'
Yes, that's fine, as long as only one thread reads, and one thread writes, at any one time.
If you have any protocol on top of the serial byte stream, you may have problems, but this is not clear from your question.
Upvotes: 0