ConcurrentQueue允许我等待一个生产者

J4N*_*J4N 6 .net c# concurrency multithreading

我有生产者/消费者的问题.目前我有一个简单的Queue包围着lock.

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

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

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

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

Yac*_*sad 3

以下是有关如何使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)