1

使用Microsoft Docs中的第二个示例,当我有一个非阻塞消费者时,当 a 中没有项目时让消费者等待的首选方法是什么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;
}

这里让消费者等待的首选方法是什么?我计划使用几个BlockingCollections 并寻找使用它的最佳方式。

4

1 回答 1

2

我建议使用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.");
于 2018-09-14T22:49:54.033 回答