multithreading - Do i need to synchronize read and write actions to the same SerialPort instance? -


Here's my scenario: I have to read and write on the same serial port in several threads. Instead of creating a serial port in each thread, which would be the reason for the 'Access Denied' error, I use global cache to work for each serial port, I only hold one serial port object.

  Private static object locker = new object (); Internal Stable Dictionary & lt; Int, serial port & gt; SerialPorts = New Dictionary & lt; Int, serialPort & gt; (); Private SerialPort GetSerialPort {Lock (Locker) {if (SerialPorts.ContainsKey (port)) {SerialPort sp = new SerialPort (port, baudrate); Sp.Open (); SerialPorts [key] = sp; }} Return SerialPorts [Key]; }   

In the read and write task, I first call GetSerialPort to get SerialPort objects. Then the related readbits and written method are called. Now my question is: without any special handling, do you have many threads to call ReadByte or methods of writing at the same time?

Yes, that's fine, as long as only one thread reads, And writes a thread at any time.

If you have a protocol at the top of the serial byte stream, then you may have problems, but this is not clear from your question.

Comments

Popular posts from this blog

java - ImportError: No module named py4j.java_gateway -

python - Receiving "KeyError" after decoding json result from url -

.net - Creating a new Queue Manager and Queue in Websphere MQ (using C#) -