这不是因为BlockingCollection
or ConcurrentQueue
,而是因为 while 循环:
while(socket.Connected)
{
while (!listOfQueueItems.IsEmpty)
{ /*code*/ }
}
当然会降低cpu;因为如果队列是空的,那么while循环就像:
while (true) ;
这反过来会吃掉cpu资源。
这不是一个很好的使用方式,ConcurrentQueue
您应该使用AutoResetEvent
它,因此无论何时添加项目,您都会收到通知。例子:
private ConcurrentQueue<Data> _queue = new ConcurrentQueue<Data>();
private AutoResetEvent _queueNotifier = new AutoResetEvent(false);
//at the producer:
_queue.Enqueue(new Data());
_queueNotifier.Set();
//at the consumer:
while (true)//or some condition
{
_queueNotifier.WaitOne();//here we will block until receive signal notification.
Data data;
if (_queue.TryDequeue(out data))
{
//handle the data
}
}
为了更好地使用 ,BlockingCollection
您应该使用GetConsumingEnumerable()
来等待添加项目,例如:
//declare the buffer
private BlockingCollection<Data> _buffer = new BlockingCollection<Data>(new ConcurrentQueue<Data>());
//at the producer method:
_messageBuffer.Add(new Data());
//at the consumer
foreach (Data data in _buffer.GetConsumingEnumerable())//it will block here automatically waiting from new items to be added and it will not take cpu down
{
//handle the data here.
}