I have an industrial equipment which is controlled by a software. The software connects to it using sockets, and keeps the connection all the time alive, while from time to time sending commands to the equipment. Now, this equipment is represented by a class which encapsulates the sending and receiving of data.Next, I need to make a UI, that will show the state of the equipment, independent from the controlling software (controlling is on a different thread same solution). Refresh to the UI must be done lets say every second, but it can happen that UI wants to read data, and the controlling software wants to write.The problem is that the equipment might respond from 50 ms to 1 second, we don't know, and during the response no one must interfere!How can I best synchronize calls to the equipment communication class?There might be at least 2 solutions:Using simple lock(obj) {} statement in C#, for each method in the common. classUsing events and a message queue with a subscriber conceptWhile the first one might be simple, I assume for my case is the worst solution because it can block everything.The second one seems more OK, but the problem is that there will be for sure some delay on receiving the results if many subscribers are, or dunno, I'm not really sure.UPDATE:I implemented using simple lock. The reason is that some equipment do not have (some do, but most not), on their controller side, the possibility to process multiple request, and their buffer will overflow. So to make sure nothing bad happens, exclusive READ/WRITE lock is best solution I have found so far, and it works.
Synchronized access to network industrial equipment
c#;multithreading;sockets;synchronization;locks
Either solution would work.  It is a generally good idea to apply a lock when writing to such values.  If you're expecting a lot of reads, then you could use ReaderWriterLockSlim to put a write lock on it, which would prevent other threads from writing the value, but it could be read with no locking whatsoever.  This assumes that the value, at any point in time in your critical area, accurately shows the state of the equipment (in other words, don't set it to zero temporarily, since another thread could read it in that moment).  I would personally favor the 2nd solution since it decouples the value being changed from thread/threads that wish to use it for some scope.  I use the ReaderWriterLockSlim in combination, however, you need not put the value change event publishing inside the critical area since you can't make any assumptions about how the event will be handled by the subscribers, even if in this case it is simply to update the UI.  Should your program change in the future, it would be easy to later adapt it to accomodate new uses for changes made to the value.Hope that helps!