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 ?
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".
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With