ConcurrentQueue<T>

ConcurrentQueue<T> is a concurrent version of the Queue<T> class. It contains three basic methods: Enqueue appends an item to the queue, TryDequeue retrieves an item from the queue if it is possible, and TryPeek gets the first element in the queue without removing it from the queue. The last two methods return false if the queue is empty.

Now let's see a sample code for ConcurrentQueue<T>:

var queue = new ConcurrentQueue<string>(); var task1 = Run(() => { AddAndPrint(queue, "[T1]: Item 1"); AddAndPrint(queue, "[T1]: Item 2"); AddAndPrint(queue, "[T1]: Item 3"); Thread.Sleep(2000); TakeAndPrint(queue); TakeAndPrint(queue); }, threadName: "T1"); var task2 = Run(() => { AddAndPrint(queue, "[T2]: Item 1"); AddAndPrint(queue, "[T2]: ...

Get Mastering C# Concurrency now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.