ConcurrentQueue
, ConcurrentStack
Queues and stacks are useful for many algorithms. We can handle elements in the order we have added them. But threads complicate matters.
With concurrent collections, located in System.Collections.Concurrent
, we can safely use stacks and queues on threads. No ordering problems occur. We use methods like TryPeek
.
ConcurrentQueue
exampleThis is a poor example of ConcurrentQueue
in a sense—it does not use multiple threads. It just shows the syntax of the queue.
ConcurrentQueue
. All methods (even ToArray
) are safe.using System;
using System.Collections.Concurrent;
class Program
{
static void Main()
{
// Create ConcurrentQueue.
ConcurrentQueue<int> queue = new ConcurrentQueue<int>();
queue.Enqueue(10);
queue.Enqueue(20);
// Display queue contents.
Console.WriteLine(string.Join(",", queue.ToArray()));
// Get first element.
if (queue.TryPeek(out int resultPeek))
{
Console.WriteLine("TryPeek result:" + resultPeek);
}
// Get and remove first element.
if (queue.TryDequeue(out int resultDequeue))
{
Console.WriteLine("TryDeque result:" + resultDequeue);
}
// Display queue again.
Console.WriteLine(string.Join(",", queue.ToArray()));
}
}10,20
TryPeek result:10
TryDeque result:10
20
ConcurrentStack
exampleThe ConcurrentStack
has similar syntax to ConcurrentQueue
. We use TryPeek
in the same way. We use TryPop
to remove an element (pop an element) from the stack.
using System; using System.Collections.Concurrent; class Program { static void Main() { // Create ConcurrentStack from array of elements. int[] elements = { 50, 10, 0 }; ConcurrentStack<int> stack = new ConcurrentStack<int>(elements); Console.WriteLine(string.Join(",", stack.ToArray())); // Push a new value to the stack. stack.Push(2000); Console.WriteLine(string.Join(",", stack.ToArray())); // Use TryPeek to get top of the stack. if (stack.TryPeek(out int resultPeek)) { Console.WriteLine("TryPeek result:" + resultPeek); } // Use TryPop to get and remove top of the stack. if (stack.TryPop(out int resultPop)) { Console.WriteLine("TryPop result:" + resultPop); } Console.WriteLine(string.Join(",", stack.ToArray())); } }0,10,50 2000,0,10,50 TryPeek result:2000 TryPop result:2000 0,10,50
Concurrent collections are useful when you need them. In many programs, they are not needed—these they just impose a performance penalty.