Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of working with ConcurrentQueue<T>
using System;
using System.Collections.Concurrent;
namespace ConcurrentQueueExample
{
class Program
{
static void Main(string[] args)
{
ConcurrentQueueAPI queueApi = new ConcurrentQueueAPI();
Console.WriteLine("Putting items in the queue.");
queueApi.AddItem("Hello");
queueApi.AddItem("World");
Console.WriteLine("\n\nIs the queue empty?");
Console.WriteLine(queueApi.NoItemsAvailable());
Console.WriteLine("\n\nHow many items do we have?");
Console.WriteLine(queueApi.ItemCount());
Console.WriteLine("\n\nLet's see the items");
while (!queueApi.NoItemsAvailable())
{
string tempString = queueApi.GetItem();
if (tempString != string.Empty)
{
Console.WriteLine(tempString);
}
}
Console.WriteLine("\n\nIs the queue empty?");
Console.WriteLine(queueApi.NoItemsAvailable());
Console.WriteLine("\n\nPress Enter to quite");
Console.ReadLine();
}
/*
* Output of the application:
* Putting items in the queue.
Adding item Hello
Adding item World
Is the queue empty?
False
How many items do we have?
2
Let's see the items
Hello
World
Is the queue empty?
True
Press Enter to quite
*/
}
class ConcurrentQueueAPI
{
private readonly ConcurrentQueue<string> _queue;
public ConcurrentQueueAPI()
{
_queue = new ConcurrentQueue<string>();
}
public void AddItem(string item)
{
Console.WriteLine($"Adding item {item}");
_queue.Enqueue(item);
}
public string GetItem()
{
if (_queue.TryDequeue(out string result))
{
return result;
}
return string.Empty;
}
public bool NoItemsAvailable()
{
return _queue.IsEmpty;
}
public int ItemCount()
{
return _queue.Count;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.