ConcurrentQueue, which allows me to wait for one producer

I have a producer / consumer problem. I currently have a simple Queue surrounded by lock .

I am trying to replace it with something more efficient.

My first choice was to use ConcurrentQueue , but I don’t see how to make my user wait for the next prepared message (without executing Thread.Sleep).

In addition, I would like to be able to clear the entire queue if its size reaches a certain number.

Can you suggest some existing class or implementation that would meet my requirements?

+5
source share
1 answer

Here is an example of how you can use the BlockingCollection class to do what you want:

 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; } } 
0
source

Source: https://habr.com/ru/post/1238625/


All Articles