Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to monitor a queue

What is the most efficient way to monitor a queue.

The follwoing piece of code is the biggest hog of resources :

/// <summary>
/// Starts the service.
/// </summary>
private void StartService()
{
    while (true)
    {
        //the check on count is not thread safe
        while (_MessageQueue.Count > 0)
        {
            Common.IMessage message;
            // the call to GetMessageFromQueue is thread safe
            if (_MessageQueue.GetMessageFromQueue(out message) == true)
            {
                if (message.RoutingInfo == Devices.Common.MessageRoutingInfo.ToDevice)
                {
                    _Port.SerialPort.WriteLine(message.Message);
                }
                if (message.RoutingInfo == Devices.Common.MessageRoutingInfo.FromDevice)
                {
                    OnDeviceMessageReceived(new Common.DeviceMessageArgs(message.Message));
                }
            }
        }
    }
}

Start Service runs on background thread , the call to _MessageQueue.Count is not thread safe , I am not locking on count in MessageQueue . I do however lock on the implementation of _MessageQueue.GetMessageFromQueue . Is the way I have gone about this efficient? Should I rather raise an event Every time the queue goes from a Count of 0 to greater than zero ?

like image 429
AndyMM Avatar asked Jun 23 '09 15:06

AndyMM


People also ask

Is a queue faster than a list?

Queue is significantly faster than List , where memory accesses are 1 vs. n for List in this use case. I have a similar use case but I have hundreds of values and I will use Queue because it is an order of magnitude faster. A note about Queue being implemented on top of List : the key word is "implemented".

Is Message Queue stateless?

Queues fan out work by releasing each message only once Therefore, each worker can process the data it receives without having to worry about whether other workers have received and processed the same data. This allows the workers to be designed in a more straightforward, stateless way.


2 Answers

You should probably include some type of thread sleep into that method, otherwise its going to be using 100% CPU. Alternatively, you could create a wait handle, and set it when you add a message to the queue.

like image 145
David Avatar answered Oct 05 '22 10:10

David


If I haven't missed anything - you're doing a busy wait on the _messageQueue.Count property. I would try doing something like is done at: http://msdn.microsoft.com/en-us/library/yy12yx1f.aspx

like image 26
RA. Avatar answered Oct 05 '22 08:10

RA.