监视队列的最有效方法

And*_*yMM 5 .net c# performance

什么是监控队列的最有效方法.

以下代码是最大的资源:

/// <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));
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Start Service在后台线程上运行,对_MessageQueue.Count的调用不是线程安全的,我没有锁定MessageQueue中的count.但是我确实锁定了_MessageQueue.GetMessageFromQueue的实现.我这样做有效吗?我是否应该提高事件每次队列从0到大于0?

Dav*_*vid 5

您可能应该在该方法中包含某种类型的线程休眠,否则它将使用100%的CPU.或者,您可以创建一个等待句柄,并在向队列添加消息时进行设置.