A
A
Artem Ivantsov2015-02-03 10:11:49
.NET
Artem Ivantsov, 2015-02-03 10:11:49

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);
                }
            }
        }

But this code is buggy. I have added the command to the list. The thread is still running, so thread creation is skipped. But the thread to send has already exited the loop and therefore will not send anything. Well, I do not have a thread to send and there is a command in the queue. What do i do?
There was an idea to use a regular thread that sleeps for a while if there are no commands in the queue. And the adding method wakes it up with an Interrupt. It turns out that I have one thread constantly hanging, which I do not like. Yes, and I, in the situation described above, the command will be sent, but with a delay equal to the sleep time.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
mayorovp, 2015-02-03
@Ramirag

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.

O
Oxoron, 2015-02-04
@Oxoron

Use a mutex, locker, or any other locking mechanism (in both methods).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question