http://dotnetpattern.com/csharp-concurrentqueue
Add Items in ConcurrentQueue
It provides an Enqueue method to add any item at the end of the queue. Enqueue takes the argument which data type matches with the type argument. Below is the example.
ConcurrentQueue<int> coll = new ConcurrentQueue<int>();
coll.Enqueue(1);
coll.Enqueue(2);
coll.Enqueue(3);
coll.Enqueue(4);
It is only method available to add item to ConcurrentQueue. Enqueue method does not have any other overloaded methods.
Retrieve/Remove Single Item
For retrieving items, we have two methods.
TryPeek
TryDequeue
TryPeek Method
TryPeek method tries to get an item from the ConcurrentQueue without removing item from the list. It returns true if operation is successful otherwise returns false. It returns the item into an out parameter. Below is the example.
ConcurrentQueue<int> coll = new ConcurrentQueue<int>();
coll.Enqueue(1);
coll.Enqueue(2);
coll.Enqueue(3);
coll.Enqueue(4);
int item;
bool isSuccessful = coll.TryPeek(out item);
Console.WriteLine(isSuccessful); //Returns True
Console.WriteLine(item); //Return "1"
As TryPeek does not remove an item from the queue, it returns the same item again an again.
TryDequeue Method
TryDequeue method tries to get an item from the ConcurrentQueue, but it removes item from the list. It also returns true if operation is successful other returns false. It returns the item into an out parameter. Below is the example.
ConcurrentQueue<int> coll = new ConcurrentQueue<int>();
coll.Enqueue(1);
coll.Enqueue(2);
coll.Enqueue(3);
coll.Enqueue(4);
int item;
bool isSuccessful = coll.TryDequeue(out item);
Console.WriteLine(isSuccessful); //Returns True
Console.WriteLine(item); //Return "1"
isSuccessful = coll.TryDequeue(out item);
Console.WriteLine(isSuccessful); //Returns True
Console.WriteLine(item); //Return "2"
In the above example, when we dequeue an item first time it returns “1” item in the out parameter. When we again use dequeue method, it returns the second item inserted in the queue that is “2”.