Skip to content

Instantly share code, notes, and snippets.

@briannipper
Created November 1, 2018 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save briannipper/c861e708874428d4dc6dda5817411c70 to your computer and use it in GitHub Desktop.
Save briannipper/c861e708874428d4dc6dda5817411c70 to your computer and use it in GitHub Desktop.
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