Answer the question
In order to leave comments, you need to log in
How to implement command queue execution in a child thread?
I have a COM port on which I send command sets to the device. The developers of the device did not implement any queue of received commands, so if you send two commands at once, the device hangs. Therefore, I need to set a small delay between sending commands. I would like to implement all this transparently so as not to think about this bug throughout the project.
How I imagine it. I have a queue of commands to send, which can be replenished. And I need these commands to be sent to the addressee sequentially in the child thread.
I wrote something like this:
private void AddCommand(Byte[] command)
{
_commandQueue.Enqueue(command);
if (_commandTask.IsCompleted)
_commandTask.Start();
}
private void SendCommand()
{
Byte[] sendBytes;
while (!_commandQueue.IsEmpty)
{
if (_commandQueue.TryDequeue(out sendBytes))
{
_port.Write(sendBytes, 0, sendBytes.Length);
Thread.Sleep(100);
}
}
}
Answer the question
In order to leave comments, you need to log in
Use a ConcurrentQueue wrapped in a BlockingCollection to pass messages between threads. The thread that reads commands from the queue can generally hang all the time - as long as it is alone and it sleeps, this is not a problem at all.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question