<.> Create the blocking queue in the .NET
The blocking queue is a queue. When the queue is over, it will block the thread of adding elements to the queue; when the queue is empty, it will block the thread of the element from the queue. This behavior ensures coordination of producers and consumers of the queue and will not be lost or repeated data.
A method of creating a blocking queue in a .NET was to realize the custom set of inheritance from
. This type can use to block threads when the queue is full or empty. However, this method is not ideal, because it requires a lot of custom code and is prone to errors.
CollectionBase
Is there a better way? AutoResetEvent
The class in the naming space provides all the functions of the blocking queue, and it is easier to use than a custom set class.
There are two main methods: and System.Collections.Concurrent
. If the queue is full, the method will block the calling thread; if the queue is empty, the BlockingCollection<T>
method will block the calling thread.
The following examples of BlockingCollection<T>
Class: Add
Take
Add
Conclusion Take
Class is a convenient and efficient method to create a blocking queue in the .NET. It is easier to use than a custom set class and provides all functions of the blocking queue. BlockingCollection<T>
The above is the detailed content of How Can I Efficiently Create a Blocking Queue in .NET?. For more information, please follow other related articles on the PHP Chinese website!