- the IConcurrentCollection<T> interface represents a collection which in a thread safe way you can add or remove from
- some implementations of this are:
- ConcurrentStack<T>
- ConcurrentQueue<T>
[1] System.Threading.Collections.ConcurrentQueue<T>
- NOTE: I will drop the System namespace below to avoid overflow but it precedes all the namespaces listed
- Threading.Collections.ConcurrentQueue<T> is a thread-safe and scalable queue data structure
- as with its Collections.Generics.Queue<T> counterpart, ConcurrentQueue<T> provides an Enqueue method for adding an element to the queue
- unlike Queue<T>, however, ConcurrentQueue<T> does not provide a Dequeue method for removing an item from the queue
- instead, it provides a TryDequeue method that returns a Boolean value indicating whether an item could be dequeued and an out parameter containing the dequeued element if one could be retrieved
- while Queue<T> provides Enqueue/Dequeue methods, ConcurrentQueue<T> provides the Enqueue/TryDequeue methods
Example: consider a loop meant to remove each element from the queue and process it
Using Queue<T> |
while (queue.Count > 0) { Data d = stack.Dequeue(); Process(d); } |
Using ConcurrentQueue<T> |
Data d; while (queue.TryDequeue(out d)) { Process(d); } |
[2] System.Threading.Collections.ConcurrentStack<T>
- ConcurrentStack<T> serves as a thread-safe alternative to Collections.Generics.Stack<T>
- while Stack<T> provides Push/Pop methods, ConcurrentStack<T> provides the Push/TryPop methods
Example:
Using Stack<T> |
Stack<T> stack = new Stack<T>(); while (stack.Count > 0) { Use(stack.Pop()); } // in this stack implmentation one would // have had to lock around the axis // of both stack.Count and stack.Pop |
Using ConcurrentStack<T> |
ConcurrentStack<T> cStack = new ConcurrentStack<T>(); T data; while (cStack.Count > 0) { Use(cStack.TryPop()); } // TryPop says try and get something and // if its available give it to me |
1 comment:
Lovely blog you hhave here
Post a Comment