[英]BlockingCollection - making consumer wait
使用Microsoft Docs的第二个示例,当我有一个非阻塞消费者时,当BlockingCollection
中没有任何项目时让消费者等待的首选方法是什么? 文档中的示例如下。
static void NonBlockingConsumer(BlockingCollection<int> bc, CancellationToken ct)
{
// IsCompleted == (IsAddingCompleted && Count == 0)
while (!bc.IsCompleted)
{
int nextItem = 0;
try
{
if (!bc.TryTake(out nextItem, 0, ct))
{
Console.WriteLine(" Take Blocked");
}
else
Console.WriteLine(" Take:{0}", nextItem);
}
catch (OperationCanceledException)
{
Console.WriteLine("Taking canceled.");
break;
}
// Slow down consumer just a little to cause
// collection to fill up faster, and lead to "AddBlocked"
Thread.SpinWait(500000);
}
Console.WriteLine("\r\nNo more items to take.");
}
上面的示例使用SpinWait
暂停使用者。
简单地使用以下内容可能会使CPU非常繁忙。
if (!bc.TryTake(out var item))
{
continue;
}
在此让消费者等待的首选方法是什么? 我打算使用几个BlockingCollection
并寻找使用它的最佳方法。
我建议使用Take
而不是TryTake
。
调用Take可能会阻塞,直到可以删除某项为止。
您在问题中提到的链接有一个很好的(阻止)示例:
while (!dataItems.IsCompleted)
{
Data data = null;
// Blocks if number.Count == 0
// IOE means that Take() was called on a completed collection.
// Some other thread can call CompleteAdding after we pass the
// IsCompleted check but before we call Take.
// In this example, we can simply catch the exception since the
// loop will break on the next iteration.
try
{
data = dataItems.Take();
}
catch (InvalidOperationException) { }
if (data != null)
{
Process(data);
}
}
Console.WriteLine("\r\nNo more items to take.");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.