Most efficient way to monitor a queue

.net, c#, performance

Solution

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.

Problem

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 ?

Original source