gpt4 book ai didi

c# - 监控队列的最有效方法

转载 作者:太空狗 更新时间:2023-10-29 22:56:18 25 4
gpt4 key购买 nike

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

下面的代码是最大的资源消耗:

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

启动服务在后台线程上运行,对 _MessageQueue.Count 的调用不是线程安全的,我没有锁定 MessageQueue 中的计数。但是,我确实锁定了 _MessageQueue.GetMessageFromQueue 的实现。我这样做的方式有效吗?我是否应该在每次队列计数从 0 变为大于零时引发事件?

最佳答案

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

关于c# - 监控队列的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1033170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com