ConcurrentQueue允许我等待一个生产者

时间:2015-12-18 10:48:43

标签: c# .net multithreading concurrency

我遇到了生产者/消费者的问题。目前,我有一个简单的Queuelock包围。

我正试图用更高效的东西取代它。

我的第一选择是使用ConcurrentQueue,但我不知道如何让我的消费者等待下一个产生的消息(没有做Thread.Sleep)。

此外,如果大小达到特定数量,我希望能够清除整个队列。

您能否建议一些符合我要求的现有课程或实施?

1 个答案:

答案 0 :(得分:0)

以下是有关如何使用BlockingCollection类来执行所需操作的示例:

BlockingCollection<int> blocking_collection = new BlockingCollection<int>();

//Create producer on a thread-pool thread
Task.Run(() =>
{
    int number = 0;

    while (true)
    {
        blocking_collection.Add(number++);

        Thread.Sleep(100); //simulating that the producer produces ~10 items every second
    }
});

int max_size = 10; //Maximum items to have

int items_to_skip = 0;

//Consumer
foreach (var item in blocking_collection.GetConsumingEnumerable())
{
    if (items_to_skip > 0)
    {
        items_to_skip--; //quickly skip items (to meet the clearing requirement)
        continue;
    }

    //process item
    Console.WriteLine(item);

    Thread.Sleep(200); //simulating that the consumer can only process ~5 items per second

    var collection_size = blocking_collection.Count;

    if (collection_size > max_size) //If we reach maximum size, we flag that we want to skip items
    {
        items_to_skip = collection_size;
    }
}