public class CControl { //Make instance of box A (hardware device 1) private CIOLayer boxA = new CIOLayer(); //Make instance of box B (hardware device 2) private CIOLayer boxB = new CIOLayer(); public CControl() { boxA.Connect("10.8.4.90"); boxB.Connect("10.8.4.91"); boxA.ExecuteCommand1(1); //Put command on a queue and execute on thread 1 boxB.ExecuteCommand1(1); //Put command on a queue and execute on thread 2 } } public class CIOLayer { private CEthernet _ethernet = new CEthernet(); private CQueue _queue = new CQueue(); private byte[] arrSend; private byte[] arrReceive; public void Connect(string IP) { _ethernet.Connect(IP); } public void ExecuteCommand1(UInt32 runID) { this._queue.AddToQueue(new CQueueEntity((par) => { //Create arrSend by looking in the protocol of the device. arrReceive = _ethernet.WriteRead(arrSend); //The result arrReceive is wrong if a static lock is not used in WriteRead(...) in CEthernet. }, new object[] { runID })); } } public class CQueue { ConcurrentQueue<CQueueEntity> _queueLowLevelCommands = new ConcurrentQueue<CQueueEntity>(); public CQueue() { this.ExecuteQueueItems(); } public void AddToQueue(CQueueEntity queueItem) { this._queueLowLevelCommands.Enqueue(queueItem); } public CQueueEntity DequeueFromQueue() {...} private void ExecuteQueueItems() { Task.Factory.StartNew(() => { while (true) { CQueueEntity queueItem = this.DequeueFromQueue(); queueItem.Execute(queueItem.Parameters); } } } } public class CEthernet { //This lock object must be static, but why? private static volatile object _processLockEthernet = new object(); private Socket _clientSock; public void Connect(string IP, int port = 6789) { this._clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); this._clientSock.Connect(IP, port); } public byte[] WriteRead(byte[] arr) { //WHY will it only work when having this STATIC lock ?? //If the lock object is not static then the received byte //array contains carbage (in 90% of the cases). //Each instance of a box have it's own instance of this CEthernet class! lock (_processLockEthernet) { _bytes = _clientSock.Send(this._byteListFromPC.ToArray()); //Wait for data while (_clientSock.Available == 0){...} byte[] received = new byte[_clientSock.Available]; _clientSock.Receive(received); return received; } } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)