Skip to content

Instantly share code, notes, and snippets.

@Acapla
Created May 23, 2014 02:51
Show Gist options
  • Save Acapla/ba2477953b0dd635c862 to your computer and use it in GitHub Desktop.
Save Acapla/ba2477953b0dd635c862 to your computer and use it in GitHub Desktop.
public class Queue<T>
{
private readonly ConcurrentQueue<T> _queue = new ConcurrentQueue<T>();
private long _count = 0;
private readonly Action<T> _action = null;
public Queue(Action<T> action)
{
_action = action;
}
public void EnqueueAsync(T item)
{
var count = Interlocked.Increment(ref _count);
_queue.Enqueue(item);
if (count == 1)
{
Task.Run(() => Dequeue());
}
}
private async void Dequeue()
{
while (true)
{
T item;
if (_queue.TryDequeue(out item))
{
_action(item);
var count = Interlocked.Decrement(ref _count);
if (count == 0)
{
return;
}
}
else
{
await Task.Yield();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment